如何识别一个文件是否是正常的文件或目录使用python

你如何检查一个文件是一个正常的文件或使用Python的目录?

os.path.isdir()os.path.isfile()应该给你你想要的。 请参阅: http : //docs.python.org/library/os.path.html

正如其他答案所说, os.path.isdir()os.path.isfile()是你想要的。 但是,您需要记住,这不是唯一的两种情况。 例如,使用os.path.islink()作为符号链接。 而且,如果这个文件不存在,这些都会返回False ,所以你可能也想用os.path.exists()来检查。

 import os if os.path.isdir(d): print "dir" else: print "file" 

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

尝试这个:

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

如果你只是通过一组目录,你可能会更好的尝试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)) 

Python 3.4将pathlib模块引入标准库,它提供了一种面向对象的方法来处理文件系统path。 相关的方法是.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 

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