要求:
合并来自不同文件夹下相同csv文件,如:
三个文件夹均含有1.csv,2.csv,3.csv等等文件,现在对文件进行合并。思路:先创建一个文件名list,然后遍历。
python代码:
data = pd.read_csv(r'filename_list.csv')
base_path = r"folder_path"
save_path = r'save_path'
folders = ['2016','2017','2018']
for index, row in data.iterrows():
fid = row['FID']
print(fid)
merged_df = pd.DataFrame()
for folder in folders:
folder_path = os.path.join(base_path, folder)
file_path = os.path.join(folder_path,f'{fid}.csv')
if os.path.exists(file_path):
# print(file_path)
data = pd.read_csv(file_path)
merged_df = pd.concat([merged_df, data])
if not merged_df.empty:
merged_df.to_csv(os.path.join(save_path, f'{fid}.csv'), index=False)
print('done!')