如何使用Python关闭所有打开的文件?
在Python中,没有本地方法可以跟踪所有打开的文件。为了做到这一点,您应该要么自己跟踪所有文件,要么始终使用with语句打开文件,它会在超出作用域或遇到错误时自动关闭文件。
例如
with open('file.txt') as f:
# 在此处对f进行操作
您还可以创建一个类来包含所有文件,并创建一个单独的close函数来关闭所有文件。
例如
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()
# 使用open方法
foo = files.open("text.txt", "r")
# 关闭所有文件
files.close()
极客教程