3

I usually use:

f = open(path,'w')
print >> f, string
f.close()

However, I saw in other's codes:

print >> open(path,'w'), string

also works well.

So, we don't have to close the file if it is opened with 'print'?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
bayesrule
  • 115
  • 7

1 Answers1

9

Yes, you still need to close the file. There is no difference with print.

Closing the file will flush the data to disk and free the file handle.

In CPython, the system will do this for you when the reference count for f drops to zero. In PyPy, IronPython, and Jython, you would need to wait for the garbage collector to run (for automatic file closing). Rather that adopt the fragile practice of relying on automatic closing by the memory manager, the preferred practice is for you to control the closing of the file.

Since explicit closing of files is a best practice, Python has provided a context manager for file objects that makes it very easy:

with open(path, 'w') as f:
    print >> f, string

This will close your file when you leave the body of the with-statement.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485