gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:33:06 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com