简体   繁体   中英

Closing a file in python opened with a shortcut

I am just beginning with python with lpthw and had a specific question for closing a file.

I can open a file with:

input = open(from_file)
indata = input.read()

#Do something

indata.close()

However, if I try to simplify the code into a single line:

indata = open(from_file).read()

How do I close the file I opened, or is it already automatically closed?

Thanks in advance for the help!

You simply have to use more than one line; however, a more pythonic way to do it would be:

with open(path_to_file, 'r') as f:
    contents = f.read()

Note that with what you are doing before, you could miss closing the file if an exception was thrown. The 'with' statement here will cause it be closed even if an exception is propagated out of the 'with' block.

Files are automatically closed when the relevant variable is no longer referenced. It is taken care of by Python garbage collection.

In this case, the call to open() creates a File object, of which the read() method is run. After the method is executed, no reference to it exists and it is closed (at least by the end of script execution).

Although this works, it is not good practice. It is always better to explicitly close a file, or (even better) to follow the with suggestion of the other answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM