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

如何使用 python 检查文件是普通文件还是目录?

26846 次浏览

os.path.isdir()os.path.isfile()应该会给你你想要的。参见: Http://docs.python.org/library/os.path.html

import os


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

Isdir (‘ string’)
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.path.isdir()os.path.isfile()是你想要的。但是,您需要记住,这不是仅有的两种情况。例如,对符号链接使用 os.path.islink()。此外,如果文件不存在,这些都会返回 False,所以您可能也想用 os.path.exists()进行检查。

Python 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

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

检查 如果 存在一个文件/目录:

os.path.exists(<path>)

检查 如果 路径是一个目录:

os.path.isdir(<path>)

检查 如果 路径就是文件:

os.path.isfile(<path>)