Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the Inline "open and write file" is the close() implicit?

Tags:

python

file

In Python (>2.7) does the code :

open('tick.001', 'w').write('test')

has the same result as :

ftest  = open('tick.001', 'w')
ftest.write('test')
ftest.close()

and where to find documentation about the 'close' for this inline functionnality ?

like image 434
philnext Avatar asked Mar 19 '11 15:03

philnext


People also ask

What happens if a file cannot be opened?

If file cannot be opened an error occurs (OSError). mode – This is where you will specify the purpose of opening a file. For example, ‘r’ (the default) value opens a file in reading mode for text files.

How to open a file in read mode and write mode?

For example, ‘r’ (the default) value opens a file in reading mode for text files. If you require writing to a text file, then use ‘w’ mode. For opening a file in write mode for appending text, use the ‘a’ value. The detailed list of modes is given in the last section. buffering – Set the buffering off or on by using an Integer value.

What are the different modes of opening a file?

There are many modes for opening a file: 1 r - open a file in read mode 2 w - opens or create a text file in write mode 3 a - opens a file in append mode 4 r+ - opens a file in both read and write mode 5 a+ - opens a file in both read and write mode 6 w+ - opens a file in both read and write mode

How do I Close a text file in C++?

Closing a File. The file (both text and binary) should be closed after reading/writing. Closing a file is performed using the fclose() function. fclose(fptr); Here, fptr is a file pointer associated with the file to be closed.


1 Answers

The close() here happens when the file object is deallocated from memory, as part of its deletion logic. Because modern Pythons on other virtual machines — like Java and .NET — cannot control when an object is deallocated from memory, it is no longer considered good Python to open() like this without a close(). The recommendation today is to use a with statement, which explicitly requests a close() when the block is exited:

with open('myfile') as f:
    # use the file
# when you get back out to this level of code, the file is closed

If you do not need a name f for the file, then you can omit the as clause from the statement:

with open('myfile'):
    # use the file
# when you get back out to this level of code, the file is closed
like image 193
Brandon Rhodes Avatar answered Sep 22 '22 12:09

Brandon Rhodes