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

วิธีปิดไฟล์ที่เปิดอยู่ทั้งหมดใน Python

Python ไม่มีวิธี native track ไฟล์ที่เปิดอยู่ทั้งหมด ต้อง track เอง หรือใช้ with statement ที่ปิดอัตโนมัติ

ตัวอย่าง with statement

with open('file.txt') as f:
    # do something with f here

หรือสร้าง class จัดการไฟล์หลายไฟล์:

ตัวอย่าง Class

class OpenFiles:
    def __init__(self):
        self.files = []
    def open(self, file_name):
        f = open(file_name)
        self.files.append(f)
        return f
    def close(self):
        list(map(lambda f: f.close(), self.files))

files = OpenFiles()
foo = files.open("text.txt", "r")
files.close()