1 回答

TA貢獻1770條經驗 獲得超3個贊
讓我們嘗試pathlib從defaultdict標準庫
我們可以構建一個子文件夾字典作為鍵,所有文件作為列表中的值。
from pathlib import Path
from collections import defaultdict
your_path = 'target_directory'
file_dict = defaultdict(list)
for each_file in Path(p).rglob('*.csv'): # change this to `.json`
file_dict[each_file.parent].append(each_file)
print(file_dict)
你的字典將是一個 Pathlib 對象的列表,它與這個有點相似,關鍵是子文件夾(我剛剛在這里打印了名稱)
{Notebooks : [test.csv,
test_file.csv,
test_file_edited.csv] ,
test_csv : [File20200610.csv,
File20201012 - Copy.csv,
File20201012.csv] }
然后我們可以遍歷字典并將每個對象保存到目標文件夾中。
for each_sub_folder,files in file_dict.items():
dfs = []
for each_file in files:
j = pd.read_json(each_file) #your read method.
dfs.append(j) # append to list.
df = pd.concat(dfs)
df.to_csv(Path(target_path).joinpath(each_sub_folder.name + '.csv'),index=False)
添加回答
舉報