2013-03-05 38 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