How to close a file in python without assigning a variable

How to close a file in python after opening it like this:

line = open("file.txt", "r").readlines()[7]

+6
source share
2 answers

It is best to use a context manager. This will automatically close the file at the end of the block and will not rely on the garbarge collection implementation details.

 with open("file.txt", "r") as f: line = f.readlines()[7] 
+5
source

There are several ways, for example, you can just use f = open(...) and del f .

If your version of Python 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 do not understand why I am understated to explain how to create the correct way to work with files. Perhaps "without assigning a variable" is simply not preferable.

+1
source

Source: https://habr.com/ru/post/900272/


All Articles