Search code examples
pythonexec

How to close .txt file after "exec" use?


I would like to use exec in a loop. Is there a need to close files after using exec?

My code:

f = exec(open("./settings.txt").read())
f.close()

Result:

AttributeError: 'NoneType' object has no attribute 'exec'

What should I do to close this file?


Solution

  • Exec is not a good practise. You can use context manager and your file will be automaticly close:

    with open("./settings.txt") as f:
        data = f.read()
    
    # File is already closed
    

    But if you want to use exec you can use:

    exec('x = open("./settings.txt")')
    data = x.read()
    x.close()