Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何识别文件是普通文件还是目录_Python - Fatal编程技术网

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

Python 如何识别文件是普通文件还是目录,python,Python,如何使用python检查文件是普通文件还是目录?os.path.isdir()和os.path.isfile()应该能满足您的需要。见: 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" 正如其他答案所说,o

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

os.path.isdir()
os.path.isfile()
应该能满足您的需要。见:

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

标准库中引入了Python 3.4,它提供了一种面向对象的方法来处理文件系统路径。相关的方法是
.is_file()
.is_dir()


在Python 2.7上也可以通过

来检查文件/目录是否存在:

os.path.exists()

要检查路径是否为目录,请执行以下操作:

os.path.isdir()

要检查路径是否为文件,请执行以下操作:

os.path.isfile()
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"
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
os.path.exists(<path>)
os.path.isdir(<path>)
os.path.isfile(<path>)