2022年 11月 5日

python判断文件或路径是否存在

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

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

import os.path
os.path.isfile(fname)
  • 1
  • 2

如果你要确定他是文件还是目录,从 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:
    # 存在
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21