python - 使用 Python 迭代文件夹时获取特定的 Excel 文件名

标签 python excel

我正在尝试从多个文件夹中提取名为“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/

相关文章:

python - pd.Series.str.lower.replace ('str' , 'replace_str' ) 不起作用但 pd.Series.str.replace。 ('STR' , 'replace_str' ) 呢?

node.js - Node Js 中的 JSON 到 Excel 转换

Excel VBA 代码性能极慢

python - 为什么cv2转换后的灰度图仍然有3个 channel ?

python - 为什么欧拉计划说我弄错了第 20 位?

python - 如何展平元组列表并删除重复项?

python - 检查数字是否为斐波那契数的函数?

vba - VBA 中的日期比较

c# - 从 C# 中查找允许用户更改打印机的 Excel 打印预览对话框

php - 为什么我的临时文件不可写入/tmp 文件夹 - linux 服务器(centos)