ZenBalance
ZenBalance

Reputation: 10307

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!

Upvotes: 0

Views: 400

Answers (2)

shelhamer
shelhamer

Reputation: 31130

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.

Upvotes: 1

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95499

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.

Upvotes: 6

Related Questions