如何检查文件是否是python中的目录或常规文件?

时间:2010-07-08 14:45:10

标签: python

  

可能重复:
  How to identify whether a file is normal file or directory using python

如何检查路径是否是python中的目录或文件?

4 个答案:

答案 0 :(得分:493)

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

答案 1 :(得分:114)

使用os.path.isdir(path)

此处有更多信息http://docs.python.org/library/os.path.html

答案 2 :(得分:56)

许多Python目录函数都在os.path module

import os
os.path.isdir(d)

答案 3 :(得分:21)

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)