How do you close a file not stored in a variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do you close a file not stored in a variable?

If you open a file without assigning the file to variable (like in the example), can you do anything with the file? Or must you assign the file to a variable in order to close it?

7th Dec 2017, 4:52 PM
Zach
2 Answers
+ 7
There's an explanation of how to use an opened file, without having to explicitly close it when you are done working with the file, it's covered in the following chapter: Python 3 Tutorial → Exceptions & Files → Working with Files Example: with open("filename.txt") as f: print(f.read()) There's a note there that says, "The file is automatically closed at the end of the with statement, even if exceptions occur within it." Hth, cmiiw
7th Dec 2017, 6:58 PM
Ipang
+ 2
file = open("test.txt", "r") print(file.read()) file.close() this will open a file test.txt in read mode, and then print the content and close the file.
7th Dec 2017, 5:09 PM
Mooaholic
Mooaholic - avatar