ResourceWarning for a file that is unclosed but UnitTest is throwing it

大憨熊 提交于 2021-02-11 15:39:15

问题


I have a function like this:

def init_cars(self, directory=''):
    #some_code
    cars = set([line.rstrip('\n') for line in open(directory + "../myfolder/all_cars.txt")])
    #some_more_code

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

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!


回答1:


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)

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()

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]


来源:https://stackoverflow.com/questions/61382815/resourcewarning-for-a-file-that-is-unclosed-but-unittest-is-throwing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!