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

Question:

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?

Asked By: jobberman

||

Answers:

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()
Answered By: Avad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.