Search code examples
pythonfilepython-re

How to close a file after reading it in a function


I've got a function that reads a text file and saves all the words into a variable. Someone told me that I should close the file after reading it but I'm not sure how to do it especially when I'm using a function.

import re

def read_file(filename):
    with open(filename, "r", encoding="utf-8") as file:
        lines = file.readlines()
        words = []
        
        for line in lines:
            words += re.findall(r'\w+', line.lower())
            
    return words

Solution

  • The file is closed due to the with statement. There is 2 ways to use files:

    f = open(...)
    # do stuff
    f.close()
    

    Or, preferred and as you have done:

    with open(...) as f:
      # do stuff
    # file is closed once the do stuff block ends
    

    The code above works because of 2 magic functions (magic functions are functions used by the compiler like __str__ that have special meaning)

    __enter__ and __exit__. These are used by the with block like this:

    with some as f:
      # stuff
    

    Means the same thing as:

    f = some.__enter__()
    # stuff
    some.__exit__()