未关闭但UnitTest正在抛出它的文件的ResourceWarning [英] ResourceWarning for a file that is unclosed but UnitTest is throwing it
问题描述
我有一个这样的功能:
def init_cars(self, directory=''):
#some_code
cars = set([line.rstrip('\n') for line in open(directory + "../myfolder/all_cars.txt")])
#some_more_code
我正在编写 unittest,当我运行它们时,出现以下错误:
I am writing unittest and when I run them, I get the following error:
ResourceWarning: unclosed file <_io.TextIOWrapper name='../myfolder/all_cars.txt' mode='r' encoding='UTF-8'>
names = set([line.rstrip('\n') for line in open(directory + "../myfolder/all_cars.txt")])
ResourceWarning: Enable tracemalloc to get the object allocation traceback
找到了一个答案,但不能应用于我可以解决的代码:Python 3:ResourceWarning:未关闭的文件 <_io.TextIOWrapper name='PATH_OF_FILE'
Found an answer but can't apply to my code that I can work out: Python 3: ResourceWarning: unclosed file <_io.TextIOWrapper name='PATH_OF_FILE'
我尝试了一些东西,做了一些代码更改,但似乎无法弄清楚.谁能给我一个代码示例,告诉我如何使用我的示例代码解决这个问题!
I tried a few things, made some code changes but can't seem to figure out. Can anyone give me a code example on how to overcome this using my example code please!
推荐答案
当文件句柄不再被引用时,Python 不会自动为您关闭它.这是令人惊讶的.例如.
Python does not automatically close a filehandle for you when it is no longer referenced. This is surprising. For example.
def foo():
f = open("/etc/passwd")
for line in f:
print(line)
即使在 foo() 返回后 f
不再可用,这也会导致 ResourceWarning.
This will result in a ResourceWarning even though f
is no longer available once foo() returns.
解决方案是明确关闭文件.
The solution is to explicitly close the file.
fh = open(directory + "../myfolder/all_cars.txt")
cars = set([line.rstrip('\n') for line in fh]
fh.close()
或者使用 with
将为您关闭文件.
Or use with
which will close the file for you.
with open(directory + "../myfolder/all_cars.txt") as fh:
cars = set([line.rstrip('\n') for line in fh]
这篇关于未关闭但UnitTest正在抛出它的文件的ResourceWarning的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!