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

Cách đóng tất cả file đã mở bằng Python?


Python không có cách native theo dõi tất cả file đã mở. Bạn tự theo dõi hoặc luôn dùng with statement mở file — tự đóng khi thoát scope hoặc gặp lỗi.

Ví dụ

with open('file.txt') as f:
    # làm gì đó với f ở đây

Bạn cũng tạo class bao file và hàm close duy nhất đóng tất cả.

Ví dụ

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()
# dùng open method
foo = files.open("text.txt", "r")
# đóng tất cả file
files.close()