classification
Title: open() and file.write() without file.close()
Type: enhancement Stage: resolved
Components: Documentation Versions: Python 3.7
process
Status: closed Resolution: duplicate
Dependencies: Superseder: Built-in module _io can lose data from buffered files in reference cycles
View: 17852
Assigned To: docs@python Nosy List: docs@python, kryptomatrix, vstinner
Priority: normal Keywords:

Created on 2019-10-21 12:12 by kryptomatrix, last changed 2019-10-21 12:20 by vstinner. This issue is now closed.

Messages (2)
msg355062 - (view) Author: (kryptomatrix) Date: 2019-10-21 12:12
Consider the following program:

f = open("out.txt", "w")
f.write("abc\n")
exit(0)

Please note the absence of f.close().
The documentation 
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
says that you should use f.close() or with f = open(), but is not clear whether the program above without f.close() is guaranteed to write. The tutorial says:
"If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times."
For me this sounds like even without f.close() the file is guaranteed to be written. If it is not guaranteed to be written, you should fix the documentation, if it is guaranteed to be written, then I will open another issue because the following program does not write into out.txt on my machine:

from sympy.core import AtomicExpr
class MyWeirdClass(AtomicExpr):
	def __init__(self):
		pass
f = open("out.txt", "w")
f.write("abc\n")
exit(0)

Note: sys.version is: "3.7.3 (default, Oct  7 2019, 12:56:13) \n[GCC 8.3.0]"
msg355063 - (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2019-10-21 12:20
The issue is a duplicate of bpo-17852.
History
Date User Action Args
2019-10-21 12:20:44vstinnersetstatus: open -> closed

superseder: Built-in module _io can lose data from buffered files in reference cycles

nosy: + vstinner
messages: + msg355063
resolution: duplicate
stage: resolved
2019-10-21 12:12:20kryptomatrixcreate