可能重複:
How to identify whether a file is normal file or directory using python如何檢查文件是否是python中的目錄或常規文件?
你如何檢查的路徑是Python中的目錄或文件?
可能重複:
How to identify whether a file is normal file or directory using python如何檢查文件是否是python中的目錄或常規文件?
你如何檢查的路徑是Python中的目錄或文件?
許多Python目錄函數位於os.path
module。
import os
os.path.isdir(d)
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
從stat文檔的教育例如:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)
不是最漂亮的解決方案,但是如果你已經有了統計結構,這可以避免通過os.path.isfile或朋友進行額外的系統調用/磁盤查找。 – 2014-05-12 18:39:52
如果你不使用絕對路徑,比如上例中,它只會檢查腳本目錄(或其中的「bob」)的存在python當前位於文件系統中) – Matthias 2016-06-21 14:08:21