当前位置:懂科普 >

综合知识

> python 看是否存在文件夹 Python 判断文件/目录是否存在

python 看是否存在文件夹 Python 判断文件/目录是否存在

1、Python 操作文件时,我们一般要先判断指定的文件或目录是否存在,不然容易产生异常。

python 看是否存在文件夹 Python 判断文件/目录是否存在

2、例如我们可以使用 os 模块的 os.path.exists() 方法来检测文件是否存在:

import os.path

os.path.isfile(fname)

3、如果你要确定他是文件还是目录,从 Python 3.4 开始可以使用 pathlib 模块提供的面向对象的方法 (Python 2.7 为 pathlib2 模块):

from pathlib import Path

my_file = Path(/path/to/file)

if my_file.is_file():

# 指定的文件存在

检测是否为一个目录:

if my_file.is_dir():

# 指定的目录存在

4、如果要检测路径是一个文件或目录可以使用 exists() 方法:

if my_file.exists():

# 指定的文件或目录存在

在 try 语句块中你可以使用 resolve() 方法来判断:

try:

my_abs_path = my_file.resolve()

except FileNotFoundError:

# 不存在

else:

# 存在

  • 文章版权属于文章作者所有,转载请注明 https://dongkepu.com/zonghezhishi/ppvg88.html