Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra file tồn tại trong Python

Kiểm tra file tồn tại bằng 2 cách:

Cách 1: os.path.isfile()

import os

os.path.isfile("d:\\Package1\\package1\\fibo.py")   # True
os.path.isfile("d:/Package1/package1/fibo.py")      # True
os.path.isfile("d:\\nonexisting.txt")               # False

# Lưu ý: backslash cần escape (\\) hoặc dùng raw string r"path" hoặc forward slash /

Cách 2: Bắt exception IOError (Python 2) / OSError (Python 3)

try:
    fo = open("d:\\nonexisting.txt", "r")
    # process file
    fo.close()
except IOError:  # Python 3: except OSError:
    print("File doesn't exist")

Khuyến nghị: Cách 1 (LBYL - Look Before You Leap) rõ ràng hơn. Cách 2 (EAFP - Easier to Ask Forgiveness than Permission) phù hợp khi race condition có thể xảy ra giữa check và open.