With statements closing files (Python)

From Python Module 4 Lesson 9: with open(“filename.txt”) as f: print(f.read()) # end code It says that the file automatically closes at the end of the with statement even if exceptions occur. Can someone explain to me how exactly it closes? My guess is that since it’s declared as a local variable, it’s nonexistent once the with statement is executed. Am I close?

10/22/2019 11:15:10 PM


3 Answers

New Answer




Using "with" will always make sure your files are closed


No, it's not like that. 'with' is called a context manager. In order to understand how with works, you must have basic understanding how classes work. It's a really easy concept, but I can't explain it in this few number of lines. Go to youtube, write: Corey Schafer context managers And click ln first link, enjoy! Here is the link to the video: https://m.youtube.com/watch?v=-aKFBoZpiqA If you still don't understand, you can repost here.