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

วิธีปิดไฟล์ที่เปิดอยู่ใน Python

ปิดไฟล์ด้วย close() บน file object:

ตัวอย่าง

>>> f = open('hello.txt', 'r')
>>> # Do stuff with file
>>> f.close()

ไม่แนะนำ เปิดแบบนี้ เพราะไม่ปลอดภัย (อาจไม่ปิดถ้า error) ใช้ with แทน:

ตัวอย่าง

with open('hello.txt', 'r') as f:
    print(f.read())

ไฟล์จะปิดอัตโนมัติเมื่อออกจาก with block