如何使用python识别文件是普通文件还是目录


Answers:



36

至于其他的答案说,os.path.isdir()os.path.isfile()你想要的东西。但是,您需要记住,这不是仅有的两种情况。使用os.path.islink()的符号链接的实例。此外,False如果文件不存在,这些都将返回,因此您可能还需要检查一下os.path.exists()


10

蟒3.4引入pathlib模块到标准库,它提供了一个面向对象的方法来处理的文件系统的路径。相对的方法是.is_file().is_dir()

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.is_file()
Out[3]: False

In [4]: p.is_dir()
Out[4]: True

In [5]: q = p / 'bin' / 'vim'

In [6]: q.is_file()
Out[6]: True

In [7]: q.is_dir()
Out[7]: False

也可以通过PyPi上的pathlib2模块在 Python 2.7 上使用Pathlib。



2

os.path.isdir('string')
os.path.isfile('string')


2

试试这个:

import os.path
if os.path.isdir("path/to/your/file"):
    print "it's a directory"
else:
    print "it's a file"

-1

如果您只是浏览一组目录,则最好尝试尝试os.chdir给出错误/警告(如果失败):

import os,sys
for DirName in sys.argv[1:]:
    SaveDir = os.getcwd()
    try:
        os.chdir(DirName)
        print "Changed to "+DirName
        # Do some stuff here in the directory
        os.chdir(SaveDir)
    except:
        sys.stderr.write("%s: WARNING: Cannot change to %s\n" % (sys.argv[0],DirName))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.