python - Python 中的 os.walk 返回一个空列表

标签 python

我正在尝试使用 os.walk从目录中返回 .xlsx 文件列表,但它返回一个空列表。

import os
import pathlib

working_directory = 'N:/files path'

def find_filenames(path, suffix):
# First save all filenames in a list: file_list:
    file_list = []
    # Gets a list of all validation xlsx files in the folder:
    for subdir, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(suffix):
                # save filesnames in file_list: 
                file_list.append(file)
            return file_list
        
print(find_filenames(pathlib.Path(working_directory), '.xlsx')
它正在打印这个:
[]
当它看起来像这样:
enter image description here
我错过了什么或做错了什么?谢谢!

最佳答案

应该是:

import os
import pathlib

working_directory = 'N:/files path'

def find_filenames(path, suffix):
# First save all filenames in a list: file_list:
    file_list = []
    # Gets a list of all validation xlsx files in the folder:
    for subdir, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(suffix):
                # save filesnames in file_list: 
                file_list.append(file)
    return file_list
问题是你把 return在错误的地方。如果您在问题中输入类似代码,并且第一个文件不以 .xlsx 结尾,它会直接返回 [] !

关于python - Python 中的 os.walk 返回一个空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67750334/

相关文章:

python - Matplotlib 一张图中的多种颜色

python - 从非 root 用户执行 root 所需的脚本

python - 在 python stanfordnlp 中使用斯坦福依赖项(而不是通用依赖项)

java - 使用Java RMI调用Python方法

python - 使用随机数列表和所有简单的数学运算符计算所有可能的组合以达到给定目标

python - 类型错误 : wrap_socket() got an unexpected keyword argument 'policy_listener' | gevent-socketio

python - 在 python 中计算大型 numpy 数组的速度和加速度

Python多重赋值问题(列表)

python - 从参数中选择所有非 None 元素并将它们放在 python 字典中的优雅方法是什么?

python - Cython 没有加速