如何使用os.listdir()忽略隐藏文件? [英] How to ignore hidden files using os.listdir()?
问题描述
我的python脚本执行一个os.listdir(path)
,其中的路径是一个队列,其中包含我需要一一对待的档案.
My python script executes an os.listdir(path)
where the path is a queue containing archives that I need to treat one by one.
问题是我要在数组中获取列表,然后只执行一个简单的array.pop(0)
.直到我将项目置于颠覆状态之前,一切都很好.现在,我在数组中找到了.svn
文件夹,这当然会使我的应用程序崩溃.
The problem is that I'm getting the list in an array and then I just do a simple array.pop(0)
. It was working fine until I put the project in subversion. Now I get the .svn
folder in my array and of course it makes my application crash.
所以这是我的问题:执行os.listdir()
时是否有一个函数可以忽略隐藏文件?如果没有,那是最好的方法?
So here is my question: is there a function that ignores hidden files when executing an os.listdir()
and if not what would be the best way?
推荐答案
您可以自己写一个:
def listdir_nohidden(path):
for f in os.listdir(path):
if not f.startswith('.'):
yield f
或者您可以使用 glob :
def listdir_nohidden(path):
return glob.glob(os.path.join(path, '*'))
其中任何一个都将忽略以'.'
开头的所有文件名.
Either of these will ignore all filenames beginning with '.'
.
这篇关于如何使用os.listdir()忽略隐藏文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!