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

clayton · 2022-04-19 20:14:51 · 热度: 8

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

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

import os.path
os.path.isfile(fname)

如果你要确定他是文件还是目录,从 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():
    # 指定的目录存在

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

if my_file.exists():
    # 指定的文件或目录存在

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

try:
    my_abs_path = my_file.resolve()
except FileNotFoundError:
    # 不存在
else:
    # 存在

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册