我正在尝试从多个文件夹中提取名为“Apples.xlsx”的 Excel 电子表格。但是,每个相同文件夹中还有另一个 Excel 电子表格“Bananas.xlsx”。当迭代我的文件夹时,我只提取“Bananas.xlsx”文件,而实际上我只需要“Apples.xlsx”文件。我尝试像这样指定“Apples.xlsx”文件:
import os
directory = os.fsencode("mydir")
for folder in os.listdir(directory):
for file in os.listdir(folder):
filename = os.fsdecode(file)
if ((filename.endswith('.xlsx')) and (filename == 'Apples.xlsx')):
filenames.append(filename)
filenames.sort()
为什么它没有提取我的“Apples.xlsx”文件?
最佳答案
我认为您只需要缩进您的 if block
,这样它就会位于您的内部 for 循环
中。我怀疑发生的情况是内部for循环
完成,因此您的if block
只会检查file
的最后一个值,这如果按字母顺序排列,将是您的“Bananas.xlsx”
import os
directory = os.fsencode("mydir")
for folder in os.listdir(directory):
for file in os.listdir(folder):
filename = os.fsdecode(file)
if ((filename.endswith('.xlsx')) and (filename == 'Apples.xlsx')):
filenames.append(filename)
filenames.sort()
关于python - 使用 Python 迭代文件夹时获取特定的 Excel 文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55656188/