Search code examples
pythonunit-testingtracemalloc

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


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!


Solution

  • 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]