How do I close a file in python after opening it this way:
line = open("file.txt", "r").readlines()[7]
How do I close a file in python after opening it this way:
line = open("file.txt", "r").readlines()[7]
Best to use a context manager. This will close the file automatically at the end of the block and doesn't rely on implementation details of the garbarge collection
with open("file.txt", "r") as f:
line = f.readlines()[7]
There are several ways, e.g you could just use f = open(...)
and del f
.
If your Python version supports it you can also use the with
statement:
with open("file.txt", "r") as f:
line = f.readlines()[7]
This automatically closes your file.
EDIT: I don't get why I'm downvoted for explaining how to create a correct way to deal with files. Maybe "without assigning a variable" is just not preferable.