简体   繁体   English

os.listdir() 不打印出所有文件

[英]os.listdir() not printing out all files

I've got a bunch of files and a few folders.我有一堆文件和几个文件夹。 I'm trying to append the zips to a list so I can extract those files in other part of the code.我正在尝试将 zip 附加到列表中,以便我可以在代码的其他部分提取这些文件。 It never finds the zips.它永远找不到拉链。

for file in os.listdir(path):
     print(file)
     if file.split(".")[1] == 'zip':
     reg_zips.append(file)

The path is fine or it wouldn't print out anything.路径很好,否则它不会打印出任何东西。 It picks up the same files each time but will not pick up any others.它每次都会选取相同的文件,但不会选取任何其他文件。 It picks up about 1/5th of the files in the directory.它获取目录中大约 1/5 的文件。

At a complete loss.完全亏本。 I've made sure that some weird race condition with the file availability isn't the problem by putting a time.sleep(3) in the code.我已经通过在代码中放置 time.sleep(3) 来确保文件可用性的一些奇怪的竞争条件不是问题。 Didn't solve it.没解决。

It's possible your files have more than one period in them.您的文件中可能有多个句点。 Try using str.endswith :尝试使用str.endswith

reg_zips = []
for file in os.listdir(path):
     if file.endswith('zip'):
         reg_zips.append(file)

Another good idea (thanks, Jean-François Fabre!) is to useos.path.splitext , which handles the extension quite nicely:另一个好主意(感谢 Jean-François Fabre!)是使用os.path.splitext ,它可以很好地处理扩展:

if os.path.splitext(file)[-1] == '.zip':
    ... 

Am even better solution, I recommend with the glob.glob function:是更好的解决方案,我推荐使用glob.glob函数:

import glob
reg_zips = glob.glob('*.zip')
reg_zips = [z for z in os.listdir(path) if z.endswith("zip")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM