使用pandas在Python中循环多个Excel文件
我知道这种问题总是被问到。 但是我很难找出最好的方法来做到这一点。
我写了一个脚本,用pandas重新格式化一个excel文件。 它工作很好。
现在我想循环多个 excel文件,进行相同的重新格式化操作,并将每个excel表格最近重新格式化的数据放在底部。
我相信第一步是要制作目录中所有excel文件的列表。 有很多不同的方法来做到这一点,所以我很难find最好的方法。
以下是我目前用来导入多个.xlsx并创build一个列表的代码。
import os import glob os.chdir('C:\ExcelWorkbooksFolder') for FileList in glob.glob('*.xlsx'): print(FileList)
我不确定是否以前的glob代码实际上创build了我需要的列表。
然后我不知道从哪里去。 下面的代码在pd.ExcelFile(File)
失败pd.ExcelFile(File)
我相信我失去了一些东西….
# create for loop for File in FileList: for x in File: # Import the excel file and call it xlsx_file xlsx_file = pd.ExcelFile(File) xlsx_file # View the excel files sheet names xlsx_file.sheet_names # Load the xlsx files Data sheet as a dataframe df = xlsx_file.parse('Data',header= None) # select important rows, df_NoHeader = df[4:] #then It does some more reformatting. '
任何帮助是极大的赞赏
你需要改变
os.chdir('C:\ExcelWorkbooksFolder') for FileList in glob.glob('*.xlsx'): print(FileList)
只是
os.chdir('C:\ExcelWorkbooksFolder') FileList = glob.glob('*.xlsx') print(FileList)
为什么这个修复它? glob
返回一个列表。 由于您将for FileList in glob.glob(...)
,您将逐个列出该列表并将结果放入FileList
。 在循环结束时, FileList
是一个文件名 – 一个string。
当你这样做的代码:
for File in FileList: for x in File:
第一行将File
分配给最后一个文件名的第一个字符(作为一个string)。 第二行将x
分配给File
的第一个(也是唯一的)字符。 这不太可能是一个有效的文件名,所以它会引发错误。
我解决了我的问题。 我使用os.listdir来读取所有的excel表格,而不是使用glob函数,循环遍历每个excel文件,重新格式化,然后将最后的数据附加到表格末尾。
#first create empty appended_data table to store the info. appended_data = [] for WorkingFile in os.listdir('C:\ExcelFiles'): if os.path.isfile(WorkingFile): # Import the excel file and call it xlsx_file xlsx_file = pd.ExcelFile(WorkingFile) # 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) #.... do so reformating, call finished sheet reformatedDataSheet reformatedDataSheet appended_data.append(reformatedDataSheet) appended_data = pd.concat(appended_data)
这就是它,它做我想要的一切。