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


this question has answer here:

i use:

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

however, saw in other's codes:

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

also works well.

so, don't have close file if opened 'print'?

yes, still need close file. there no difference print.

closing file flush data disk , free file handle.

in cpython, system when reference count f drops zero. in pypy, ironpython, , jython, need wait garbage collector run (for automatic file closing). rather adopt fragile practice of relying on automatic closing memory manager, preferred practice control closing of file.

since explicit closing of files best practice, python has provided context manager file objects makes easy:

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

this close file when leave body of with-statement.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -