os.listdir()不会打印出所有文件 [英] os.listdir() not printing out all files

查看:73
本文介绍了os.listdir()不会打印出所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆文件和几个文件夹.我正在尝试将zip追加到列表中,以便可以在代码的其他部分中提取这些文件.它永远找不到拉链.

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. It never finds the zips.

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

该路径很好,否则将不会打印出任何内容.每次都会拾取相同的文件,但不会拾取其他文件.它会拾取目录中大约1/5的文件.

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.

完全丧失.我通过在代码中放置time.sleep(3)来确保文件可用性的某些怪异的竞争条件不是问题.没解决.

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. Didn't solve it.

推荐答案

文件中可能包含多个句点.尝试使用 str.endswith :

It's possible your files have more than one period in them. Try using str.endswith:

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

另一个好主意(感谢Jean-FrançoisFabre!)是使用 os.path.splitext ,可以很好地处理扩展名:

Another good idea (thanks, Jean-François Fabre!) is to use os.path.splitext, which handles the extension quite nicely:

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

一个更好的解决方案,我建议使用 glob.glob 函数:

Am even better solution, I recommend with the glob.glob function:

import glob
reg_zips = glob.glob('*.zip')

这篇关于os.listdir()不会打印出所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆