如何使用Python关闭所有打开的文件?
python中没有办法原生跟踪所有打开的文件。为此,您应该自己跟踪所有文件,或者始终使用with语句打开文件,当文件超出范围或遇到错误时,该文件会自动关闭文件。
例如
with open('file.txt') as f:
# do something with f here您还可以创建一个类来封装所有文件,并创建一个单独的关闭函数以关闭所有文件。
例如
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()# use open method
foo = files.open("text.txt", "r")
# close all files
files.close()热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短