0

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!

1

2 Answers 2

6

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.

1
  • Thanks! Looked it up and will get my head around the with statement!
    – ZenBalance
    Commented Jul 11, 2011 at 17:53
1

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.

3
  • 1
    It should be noted that relying on the GC to close your file handles is very bad practice, especially if you end up writing to it.
    – Daenyth
    Commented Jul 6, 2011 at 0:32
  • 1
    It also possibly won't work on other Python implementations that use a different GC strategy (PyPy, Jython, possibly IronPython). Such Pythons will close your file at an undetermined point sometime after the open file goes out of scope, possibly not until the process ends. This causes problems if you think of your files as being automatically closed as soon as they go out of scope.
    – Ben
    Commented Jul 6, 2011 at 4:16
  • Awesome, that explains a lot. I had a feeling doing it the first way was better (but the tutorial challenges you to do it in a single line). Thanks for the comment!
    – ZenBalance
    Commented Jul 9, 2011 at 18:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.