如何在函数中读取文件后关闭文件
How to close a file after reading it in a function
我有一个函数可以读取文本文件并将所有单词保存到一个变量中。有人告诉我应该在阅读后关闭文件,但我不确定如何关闭文件,尤其是在使用函数时。
import re
def read_file(filename):
with open(filename, "r", encoding="utf-8") as file:
lines = file.readlines()
words = []
for line in lines:
words += re.findall(r'\w+', line.lower())
return words
一旦退出打开文件的 with
块,文件就会关闭。
由于 with
语句,文件已关闭。有两种使用文件的方法:
f = open(...)
# do stuff
f.close()
或者,首选并像您所做的那样:
with open(...) as f:
# do stuff
# file is closed once the do stuff block ends
上面的代码之所以有效,是因为有 2 个魔术函数(魔术函数是编译器使用的函数,如 __str__
具有特殊含义)
__enter__
和 __exit__
。
这些由 with
块使用,如下所示:
with some as f:
# stuff
与以下含义相同:
f = some.__enter__()
# stuff
some.__exit__()
我有一个函数可以读取文本文件并将所有单词保存到一个变量中。有人告诉我应该在阅读后关闭文件,但我不确定如何关闭文件,尤其是在使用函数时。
import re
def read_file(filename):
with open(filename, "r", encoding="utf-8") as file:
lines = file.readlines()
words = []
for line in lines:
words += re.findall(r'\w+', line.lower())
return words
一旦退出打开文件的 with
块,文件就会关闭。
由于 with
语句,文件已关闭。有两种使用文件的方法:
f = open(...)
# do stuff
f.close()
或者,首选并像您所做的那样:
with open(...) as f:
# do stuff
# file is closed once the do stuff block ends
上面的代码之所以有效,是因为有 2 个魔术函数(魔术函数是编译器使用的函数,如 __str__
具有特殊含义)
__enter__
和 __exit__
。
这些由 with
块使用,如下所示:
with some as f:
# stuff
与以下含义相同:
f = some.__enter__()
# stuff
some.__exit__()