【发布时间】:2016-09-20 16:34:57
【问题描述】:
我知道一直有人问这种类型的问题。但是我很难找出最好的方法来做到这一点。
我编写了一个脚本,它使用 pandas 重新格式化单个 excel 文件。 效果很好。
现在我想循环遍历多个个excel文件,执行相同的重新格式化,并将每个excel表中新重新格式化的数据一个接一个地放在底部。
我相信第一步是列出目录中所有的 excel 文件。 有很多不同的方法可以做到这一点,所以我很难找到最好的方法。
以下是我目前用于导入多个 .xlsx 并创建列表的代码。
import os
import glob
os.chdir('C:\ExcelWorkbooksFolder')
for FileList in glob.glob('*.xlsx'):
print(FileList)
我不确定之前的 glob 代码是否真的创建了我需要的列表。
然后我很难理解从那里去哪里。
下面的代码在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.
'
非常感谢任何帮助
【问题讨论】:
-
检查缩进。 Python 中的空格和缩进很重要。此外,您应该避免在 python 中使用
File或file作为任何类型的变量名,因为file是内置的。 -
谢谢!那是个问题。
标签: python excel for-loop pandas