Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No need to close the file if it is opened with 'print' in Python? [duplicate]

Tags:

python

file

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'?

like image 900
bayesrule Avatar asked Dec 22 '25 10:12

bayesrule


1 Answers

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.

like image 163
Raymond Hettinger Avatar answered Dec 24 '25 00:12

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!