未关闭但 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

我正在编写单元测试,当我 运行 它们时,出现以下错误:

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 不会自动为您关闭它。这令人惊讶。例如。

def foo():
    f = open("/etc/passwd")
    for line in f:
        print(line)

即使 f 一旦 foo() returns.

不再可用,这将导致 ResourceWarning

解决办法是显式关闭文件。

fh = open(directory + "../myfolder/all_cars.txt")
cars = set([line.rstrip('\n') for line in fh]
fh.close()

或使用 with 将为您关闭文件。

with open(directory + "../myfolder/all_cars.txt") as fh:
  cars = set([line.rstrip('\n') for line in fh]