如何使用 os.listdir() 忽略隐藏文件?
我的 python 脚本执行一个 os.listdir(path) ,其中路径是一个队列,其中包含我需要一一处理的档案。
问题是我在数组中获取列表,然后只执行一个简单的 array.pop(0)
。在我将项目置于 subversion 之前,它工作得很好。现在我在数组中得到了 .svn 文件夹,当然它会使我的应用程序崩溃。
所以这是我的问题:是否有一个函数可以在执行 os.listdir() 时忽略隐藏文件,如果没有,最好的方法是什么?
My python script executes an os.listdir(path)
where the path is a queue containing archives that I need to treat one by one.
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以自己编写一个:
或者您可以使用 glob:
其中任何一个都会忽略所有文件名以
'.'
开头。You can write one yourself:
Or you can use a glob:
Either of these will ignore all filenames beginning with
'.'
.这是一个老问题,但似乎缺少使用列表理解的明显答案,因此我将其添加到此处以确保完整性:
作为旁注,文档状态
listdir
将返回结果“任意顺序”,但常见的用例是按字母顺序排序。如果您希望目录内容按字母顺序排序而不考虑大小写,您可以使用:(编辑为使用
key=str.lower
而不是lambda
)This is an old question, but seems like it is missing the obvious answer of using list comprehension, so I'm adding it here for completeness:
As a side note, the docs state
listdir
will return results in 'arbitrary order' but a common use case is to have them sorted alphabetically. If you want the directory contents alphabetically sorted without regards to capitalization, you can use:(Edited to use
key=str.lower
instead of alambda
)在 Windows、Linux 和 OS X 上:
On Windows, Linux and OS X:
Joshmaker 对您的问题有正确的解决方案。
如何使用 os.listdir() 忽略隐藏文件?
然而,在Python 3中,建议使用pathlib而不是os.pathlib。
Joshmaker has the right solution to your question.
How to ignore hidden files using os.listdir()?
In Python 3 however, it is recommended to use pathlib instead of os.
glob:(
glob
声称使用listdir
和fnmatch
在底层,但它也会检查前导'.'
,而不是使用fnmatch
。)glob:
(
glob
claims to uselistdir
andfnmatch
under the hood, but it also checks for a leading'.'
, not by usingfnmatch
.)我认为循环遍历所有项目的工作量太大。我更喜欢这样简单的东西:
如果目录包含多个隐藏文件,那么这会有所帮助:
对于平台独立性,正如 @Josh 提到的,glob 效果很好:
I think it is too much of work to go through all of the items in a loop. I would prefer something simpler like this:
If the directory contains more than one hidden files, then this can help:
for platform independence as @Josh mentioned the glob works well:
您只需使用一个简单的 for 循环即可排除任何包含“.”的文件或目录。
专业人士代码:
菜鸟代码
You can just use a simple for loop that will exclude any file or directory that has "." in the front.
Code for professionals:
Code for noobs