2

I've seen that the best practice for working with files in Python is to use the with block:

with open('file', 'r') as fi:
 text = fi.read()

with open('file', 'w') as fi:
  fi.write(text)

This way the files are automatically closed after you're done with them. But I get lazy, and in quick one-shot scripts I tend to do this instead:

text = open('file', 'r').read()
open('file', 'w').write(text)

Now obviously if I'm writing Real Softwareâ„¢ I should use the former, but I'd like to know what consequences the latter has (if any)?

1 Answers1

6

On CPython: None; the files will be closed when their reference count drops to 0, which is immediately when the .read() and .write() calls return.

On other Python implementations that do not use reference counting, the file will remain open until garbage collected.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343