Jes*_*sky 530

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

  • 如果你没有使用绝对路径,就像在例子中一样,它只会检查脚本目录中的"bob"是否存在(或者python当前位于文件系统中) (8认同)
  • 那是因为你没有在那里使用完整路径。使用 `os.path.isfile("/path/to/1.mp4")` (2认同)
  • @cs95,您必须先检查文件是否存在,然后检查它是否是目录。如果文件不存在,它就不可能是目录!您正在寻找 os.path.exists:https://docs.python.org/3/library/os.path.html#os.path.exists (2认同)

Jor*_*dan 122

使用 os.path.isdir(path)

更多信息请访问http://docs.python.org/library/os.path.html


Chr*_* B. 63

许多Python目录函数都在os.path模块中.

import os
os.path.isdir(d)
Run Code Online (Sandbox Code Playgroud)


Yup*_*ing 21

统计文档中的教育示例:

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)
Run Code Online (Sandbox Code Playgroud)

  • 不是最漂亮的解决方案,但如果你已经有了一个stat结构,这可以让你避免通过os.path.isfile或朋友进行额外的系统调用/磁盘搜索. (2认同)