![](/img/trans.png)
[英]ResourceWarning: unclosed file error while running python selenium unittest
[英]ResourceWarning for a file that is unclosed but UnitTest is throwing it
我有一个像这样的 function:
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 ,当我运行它们时,出现以下错误:
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: unclosed file <_io.TextIOWrapper name='PATH_OF_FILE'
我尝试了一些事情,做了一些代码更改,但似乎无法弄清楚。 谁能给我一个关于如何使用我的示例代码克服这个问题的代码示例!
Python 在不再引用文件句柄时不会自动为您关闭它。 这是令人惊讶的。 例如。
def foo():
f = open("/etc/passwd")
for line in f:
print(line)
即使 foo() 返回后f
不再可用,这也会导致 ResourceWarning。
解决方案是显式关闭文件。
fh = open(directory + "../myfolder/all_cars.txt")
cars = set([line.rstrip('\n') for line in fh]
fh.close()
或使用with
which 将为您关闭文件。
with open(directory + "../myfolder/all_cars.txt") as fh:
cars = set([line.rstrip('\n') for line in fh]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.