0

In the case of a chained method when opening a file, eg.:

indata = open(from_file).read()

Is it necessary (or possible) to close the file handle opened with the open() function?

If not, is it best practice to instead do:

infile = open(from_file)
indata = infile.read()
infile.close()

1 Answer 1

2

In the case of a chained method when opening a file

This is the pitfall of chained method to open files, so the suggested solution is to use the with clause. The lifetime of an object is within the with block and the fileObj is closed automatically

with open(from_file) as fin:
    indata = fin.read()

Why it is wrong?

  1. You are at the mercy of GC to close files
  2. If exception happens, you may not know where the exception happened, while opening or while reading

The other code piece

infile = open(from_file)
indata = infile.read()
infile.close()

Has also its pitfall.

  1. If an exception happens, the file may not be closed
  2. The code might take a different route and the close statement may not be exceuted
5
  • Thanks for the response. This makes a lot of sense. I avoided the use of exceptions at this point as I am working through Learn Python the Hard Way, and haven't hit that point in the book yet. I understand that there is plenty that could go wrong opening files, so there needs to be exception handling down the track. Commented Mar 1, 2013 at 5:34
  • With regards to "You are at the mercy of GC to close files", is it then better to use close() to be explicit or is the 'with' statement here a best practice in the Python community? Commented Mar 1, 2013 at 5:37
  • @shrodes: The with statement is not just better, its the only way to do it.
    – Abhijit
    Commented Mar 1, 2013 at 5:38
  • What about a try-except-finally where the finally contains a close()? Is this a valid way of doing things? Commented Mar 1, 2013 at 5:41
  • @shrodes: with is syntactic sugar for a try/finally block. See PEP 343 for the somewhat complicated details.
    – Blckknght
    Commented Mar 1, 2013 at 6:35

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