我正在学习使用pandas如何将excel表格进行批量合并的操作。一切都没有问题,但是我想进一步优化整理,例如将文件分类好,就会出现FileNotFoundError的报错
import pandas as pd
import os
TMG_df = pd.DataFrame()
ALPY_df = pd.DataFrame()
for file in os.listdir('source/'):
if file.startswith('Unlock_'):
TMG_df = TMG_df.append(pd.read_excel(file,dtype='object'))
for file in os.listdir('source/'):
if file.endswith('.csv'):
ALPY_df = ALPY_df.append(pd.read_csv(file, dtype='object'))
NewWriteExcel = pd.ExcelWriter('source/最终合并.xlsx')
TMG_df.to_excel(NewWriteExcel, index=False, sheet_name='TMG RAW DATA')
ALPY_df.to_excel(NewWriteExcel, index=False, sheet_name='ALPY RAW DATA')
NewWriteExcel.close()
print('合并成功')
FileNotFoundError: [Errno 2] No such file or directory: 'Unlock_ExportOrderList12716155107.xlsx'
路径写错了,你要带上前面的相对路径
TMG_df = TMG_df.append(pd.read_excel('source/'+file,dtype='object'))
在你的print哪里先print一下os.getcwd(),看看你的当前路径,我感觉你要把你的那个append的file要改成"./source"+file
当前py文件与xlsx文件并未在同一目录下,所以文件未找到,应该将路径写正确。“source/”+file为正确路径
建议用glob,就不怕路径写错了
这篇文章讲的很详细,请看:Python在导入文件时的FileNotFoundError解决办法