No need to close the file if it is opened with 'print' in Python? -
this question has answer here:
- is explicitly closing files important? 5 answers
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
Post a Comment