If you open a file using the 'with' statement, do you still need to close the file object?

To open files, I got used to the obviously outdated syntax:

f = open("sub_ranks.txt","r+") for line in f: ... f.close() 

I was told to use this syntax a couple of times now.

 with open("sub_ranks.txt", "r+") as f: for line in f: ... 

Is the "close" statement file object still necessary in the second example when the "with" statement is used?

And if so, is there any specific reason to use the c instruction to read files? In this case, it is (a bit) more verbose.

+4
python file import
Jan 22 '14 at 6:33
source share
3 answers

The answer to your question is no. The with block guarantees that the file will be closed when the control leaves the block for any reason, including exceptions (well, excluding someone pulling the power cord on your computer and some other rare events).

Therefore, it is recommended that you use the with block.

Now, perhaps by opening the file for reading only, and then unable to close it, this is not a problem. When garbage collection arrives (when possible), this file will also be closed if there is no longer a link to it; what happens when your program exits. In fact, a few code examples in white papers neglect to close a file that was open for read-only access. When writing a file or using the "read plus" mode, as in your example, you definitely need to close the file. There are many questions about how it works with incomplete / damaged files due to the inability to close them.

+3
Jan 22 '14 at 6:41
source share

From the python docs, I see that with syntactic sugar for try / finally blocks. So,

 Is a file object "close" statement still needed in the second example, when the "with" statement is being used? 

No.

In Python docs:

The 'with' statement refines the code that would have been used before, try ... finally block to ensure that the cleanup code runs. In this section, Ill discusses the statement as it will be commonly used. In the next section, Ill examine implementation details and show how to write objects for use with this statement.

The 'with' operator is a control flow structure, the basic structure of which is:

with the expression [as variable]: with-block

The expression is evaluated, and it should lead to supports the context management protocol (that is, it has enter () and exit ()).

Here is another article that makes it clear.

+2
Jan 22 '14 at 6:35
source share

No.

Suppose you want to print the host name as follows:

 with open("/etc/hostname","r") as f: print f.read() 

It will open the file, do its work and close the file.

0
Sep 10 '17 at 5:23
source share



All Articles