一般來說,使用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