0

我有这样的功能:

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'

我尝试了一些东西,做了一些代码更改,但似乎无法弄清楚。 谁能给我一个关于如何使用我的示例代码克服这个问题的代码示例!

4

1 回答 1

2

当不再引用文件句柄时,Python 不会自动为您关闭文件句柄。这是令人惊讶的。例如。

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

这将导致 ResourceWarning 即使ffoo() 返回后不再可用。

解决方案是显式关闭文件。

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

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

with open(directory + "../myfolder/all_cars.txt") as fh:
  cars = set([line.rstrip('\n') for line in fh]
于 2020-04-23T10:03:07.990 回答