我有一系列格式如下的文件:
file_1991.xlsx
file_1992.xlsx
# there are some gaps in the file numbering sequence
file_1995.xlsx
file_1996.xlsx
file_1997.xlsx
对于每个文件我想做这样的事情:
import pandas as pd
data_1995 = pd.read_excel(open(directory + 'file_1995', 'rb'), sheetname = 'Sheet1')
对数据做一些处理,并将其保存为另一个文件:
output_1995 = pd.ExcelWriter('output_1995.xlsx')
data_1995.to_excel(output_1995,'Sheet1')
我如何遍历多个文件并在多个文件中重复相同的操作,而不是对每个文件都执行所有这些操作?换句话说,我想遍历所有文件(它们大多遵循名称中的数字序列,但序列中存在一些间隙)。
提前感谢您的帮助。
最佳答案
您可以使用 os.listdir或 glob列出目录中所有文件的模块。
有了os.listdir,你可以使用fnmatch像这样过滤文件(也可以使用正则表达式);
import fnmatch
import os
for file in os.listdir('my_directory'):
if fnmatch.fnmatch(file, '*.xlsx'):
pd.read_excel(open(file, 'rb'), sheetname = 'Sheet1')
""" Do your thing to file """
或者使用 glob 模块(它是 fnmatch + listdir 的快捷方式),你可以像这样(或使用正则表达式)做同样的事情:
import glob
for file in glob.glob("/my_directory/*.xlsx"):
pd.read_excel(open(file, 'rb'), sheetname = 'Sheet1')
""" Do your thing to file """
关于Python遍历多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499498/