python 怎么判断文件是不是存在

一般来说,使用try来尝试打开一个文件是很安全的,可以检测到许多异常(比如文件损坏),但如果单纯只是判断文件是否存在,而不马上打开,可以用以下方法。

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

如果你需要确定它是不是一个文件,那可以用pathlib模块(python3.4之后),或者pathlib2(python2.7):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # 文件存在

如果想知道目录是否存在,那可以这样写:

if my_file.is_dir():
    # 文件夹存在

或者只是想知道这个文件或者文件夹是否存在

if my_file.exists():
    # 路径存在

或者用resolve()try结构里面:

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

摘选自:https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-using-python

你可能感兴趣的:(python 怎么判断文件是不是存在)