Oct-18-2019, 10:27 PM
(Oct-18-2019, 01:39 PM)perfringo Wrote:I'm assuming that no other process messes with it. The question is whether this script is guaranteed to write, because the following script does not write into the file:(Oct-18-2019, 01:20 PM)kryptomatrix Wrote: Is it guaranteed, that "out.txt" will contain "abc"
Only taxes and death are guaranteed, everything else is optional .
In more serious note - this 'guarantee' can't be given as there might be another processes which can overwrite the file. Yes, 'abc' will be written into file but this is not the same that 'guaranteed to contain' in some point after the writing.
from sympy.core import AtomicExpr class MyWeirdClass(AtomicExpr): def __init__(self): pass f = open("out.txt", "w") f.write("abc\n")I am looking for a point in the official specification that says whether this is guaranteed to write or not. Because if it is guaranteed to write, this is a bug in python.
(Oct-18-2019, 01:31 PM)buran Wrote: use with context managerI know the with keyword, but that wasn't the question. The question was if the standard guarantees that the my weird code works.
with open("out.txt", "w") as f: f.write("abc\n")it will close it for you
from the docs:
Quote:It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:
>>> >>> with open('workfile') as f: ... read_data = f.read() >>> # We can check that the file has been automatically closed. >>> f.closed TrueIf you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it. 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.