我目前有这段代码,它可以完美地执行。
它会循环读取一个文件夹中的Excel文件, 删除前两行,然后将它们另存为单独的Excel文件, 同时也将每个循环内的文件作为附加文件保存。
目前,附加文件每次运行代码时都会覆盖现有的文件。
我需要将新数据追加到已存在的Excel表格底部('master_data.xlsx)。
dfList = []
path = 'C:\\Test\\TestRawFile'
newpath = 'C:\\Path\\To\\New\\Folder'
for fn in os.listdir(path):
# Absolute file path
file = os.path.join(path, fn)
if os.path.isfile(file):
# Import the excel file and call it xlsx_file
xlsx_file = pd.ExcelFile(file)
# View the excel files sheet names
xlsx_file.sheet_names
# Load the xlsx files Data sheet as a dataframe
df = xlsx_file.parse('Sheet1',header= None)
df_NoHeader = df[2:]
data = df_NoHeader
# Save individual dataframe
data.to_excel(os.path.join(newpath, fn))
dfList.append(data)
appended_data = pd.concat(dfList)
appended_data.to_excel(os.path.join(newpath, 'master_data.xlsx'))
我原以为这会是一个简单的任务,但好像并不是。 我认为我需要将master_data.xlsx文件作为数据帧导入,然后将索引与新附加的数据匹配,并将其保存回去。或者也许有更简单的方法。任何帮助都将不胜感激。