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?
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
+ 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.