os.listdir() 没有打印出所有文件
os.listdir() not printing out all files
我有一堆文件和几个文件夹。我正在尝试将 zips 附加到列表中,以便我可以在代码的其他部分提取这些文件。它永远找不到拉链。
for file in os.listdir(path):
print(file)
if file.split(".")[1] == 'zip':
reg_zips.append(file)
路径没问题,否则不会打印出任何内容。它每次都拾取相同的文件,但不会拾取任何其他文件。它会选取目录中大约 1/5 的文件。
完全不知所措。我已经通过在代码中放置 time.sleep(3) 来确保文件可用性的一些奇怪的竞争条件不是问题。没解决。
您的文件中可能有多个句号。尝试使用 str.endswith
:
reg_zips = []
for file in os.listdir(path):
if file.endswith('zip'):
reg_zips.append(file)
另一个好主意(感谢 Jean-François Fabre!)是使用 os.path.splitext
,它可以很好地处理扩展:
if os.path.splitext(file)[-1] == '.zip':
...
更好的解决方案,我建议使用 glob.glob
函数:
import glob
reg_zips = glob.glob('*.zip')
reg_zips = [z for z in os.listdir(path) if z.endswith("zip")]
我有一堆文件和几个文件夹。我正在尝试将 zips 附加到列表中,以便我可以在代码的其他部分提取这些文件。它永远找不到拉链。
for file in os.listdir(path):
print(file)
if file.split(".")[1] == 'zip':
reg_zips.append(file)
路径没问题,否则不会打印出任何内容。它每次都拾取相同的文件,但不会拾取任何其他文件。它会选取目录中大约 1/5 的文件。
完全不知所措。我已经通过在代码中放置 time.sleep(3) 来确保文件可用性的一些奇怪的竞争条件不是问题。没解决。
您的文件中可能有多个句号。尝试使用 str.endswith
:
reg_zips = []
for file in os.listdir(path):
if file.endswith('zip'):
reg_zips.append(file)
另一个好主意(感谢 Jean-François Fabre!)是使用 os.path.splitext
,它可以很好地处理扩展:
if os.path.splitext(file)[-1] == '.zip':
...
更好的解决方案,我建议使用 glob.glob
函数:
import glob
reg_zips = glob.glob('*.zip')
reg_zips = [z for z in os.listdir(path) if z.endswith("zip")]