Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีตรวจสอบว่าไฟล์มีอยู่จริงใน Python

ตรวจสอบไฟล์ได้ 2 วิธี:

วิธีที่ 1: ใช้ os.path.isfile()

ฟังก์ชันคืน True หากไฟล์ที่ Path ระบุมีอยู่ False หากไม่มี

>>> 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

หมายเหตุ: Backslash ใน Path ต้องเขียนคู่ \\ เพื่อ Escape ใน Python String

วิธีที่ 2: จับ Exception IOError

พยายามเปิดไฟล์ด้วย open() หากไฟล์ไม่มี จะ Raise IOError

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