Why when i use this method i don't need to close the file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why when i use this method i don't need to close the file

I tried this with open('hw.txt',mode='w')as f: f.write('hello world') And i didn't need to close the file

24th Feb 2019, 9:44 AM
Mahmoud Mansour
Mahmoud Mansour - avatar
2 Answers
+ 5
The with block is called a context manager. The variable f is only valid within the with block. As soon as you leave the block, you're basically telling the interpreter that you're not going to use the file (which is associated with the variable f) anymore. So there is no reason to keep the file open and python closes it automatically for you.
24th Feb 2019, 10:22 AM
Anna
Anna - avatar
0
Thank you ❤
24th Feb 2019, 12:46 PM
Mahmoud Mansour
Mahmoud Mansour - avatar