1. 程式人生 > >python中判斷一個檔案是否存在

python中判斷一個檔案是否存在

你可以使用os.path.isfile,如果存在,它會返回True.如下:

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

或者使用os.path.exists

import os.path
os.path.exists(file_path)

isfile和exists有一些區別,isfile判斷是否是檔案,exists判斷檔案是否存在:

>>> print os.path.isfile("/etc/password.txt")
True
>>> print os.path.isfile("/etc"
) False >>> print os.path.isfile("/does/not/exist") False >>> print os.path.exists("/etc/password.txt") True >>> print os.path.exists("/etc") True >>> print os.path.exists("/does/not/exist") False

從python3.4開始,pathlib模組提供了類似的方法:

from pathlib import Path
my_file = Path(“/path/to/file”)
if my_file.is_file():