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

ฟังก์ชัน close() ใน Python ทำอะไร?

close() ปิดไฟล์ที่เปิดอยู่:

f = open('my_file', 'r+')
my_file_data = f.read()
f.close()

OS มอบ file handle ต้องปิดเมื่อใช้เสร็จ หาก error ไม่ได้ close() จะ leak handle ใช้ with ปิดอัตโนมัติ:

with open('my_file', 'r+') as f:
    my_file_data = f.read()