2013-03-05 130 views
1

在使用os.path.getsize()和os.path.isfile时,我的脚本也返回了.DS_Store文件,这也是我不需要的。我如何忽略这些?如何忽略python函数中的隐藏文件?

import os 

root = "/Users/Siddhartha/Desktop/py scripts" 
for item in os.listdir(root): 
    if os.path.isfile(os.path.join(root, item)): 
     print item 
+2

'item.startswith( “”)'? – 2013-03-05 23:02:59

+0

您是否试图忽略只有'.DS_Store',Finder认为“隐藏”的任何内容,Finder认为“隐藏”的任何内容或其在每个平台上的相应内容,......? – abarnert 2013-03-05 23:09:07

+0

或者,也许它是http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection/6365265#6365265的一个替代,取决于这个问题的答案。 – abarnert 2013-03-05 23:11:41

回答

8

假设你要忽略与.开头的文件:

import os 

root = "/Users/Siddhartha/Desktop/py scripts" 
for item in os.listdir(root): 
    if not item.startswith('.') and os.path.isfile(os.path.join(root, item)): 
     print item 
+0

哦,我明白了。隐藏文件是否始终以一段时间开始?谢谢! – user2063763 2013-03-05 23:04:24

+2

在某些操作系统上是这种情况,但不适用于Windows。对于更通用的解决方案,请参阅此答案:http://stackoverflow.com/a/6365265/505154 – 2013-03-05 23:06:39

+0

对于Mac OS X来说也是如此,这是OP关心的问题。文件可以通过属性在文件系统级隐藏。最重要的是,就NSOpenPanel(或Finder.app)而言,它们可以隐藏在Finder Info级别,或者隐含规则,如“不显示”〜/ Library“(在10.7+ )等等 – abarnert 2013-03-05 23:15:40