With statements closing files (Python) | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

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?

22nd Oct 2019, 11:15 PM
ź§ą¼ŗ Jenspi ą¼»ź§‚
ź§ą¼ŗ Jenspi ą¼»ź§‚ - avatar
1 Resposta
+ 4
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.
22nd Oct 2019, 11:45 PM
Aymane Boukrouh
Aymane Boukrouh - avatar