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!
Python does not automatically close a filehandle for you when it is no longer referenced. This is surprising. For example.
This will result in a ResourceWarning even though
f
is no longer available once foo() returns.The solution is to explicitly close the file.
Or use
with
which will close the file for you.