Python Forum
Does python guarantees that file.write() works without file.close() ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Does python guarantees that file.write() works without file.close() ?
#1
Long story short: Is it guaranteed, that "out.txt" will contain "abc" after executing the following program:
f = open("out.txt", "w")
f.write("abc\n")
I'm not sure, whether the Standard guarantees if the file destructor flushes the file.
Reply
#2
use with context manager
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
True
If 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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(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 Smile.

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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
(Oct-18-2019, 01:39 PM)perfringo Wrote:
(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 Smile.

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.
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:
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 manager
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
True
If 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.
I know the with keyword, but that wasn't the question. The question was if the standard guarantees that the my weird code works.
Reply
#5
(Oct-18-2019, 10:27 PM)kryptomatrix Wrote: The question was if the standard guarantees that the my weird code works.
No,it will depend on how run the file and what's used eg some editor may write and other not.
Running from command line it will work as it just open the interpreter and close it.
C:\code\read
λ python test_write.py

C:\code\read
If i now do the same but open it in interactive shell.
C:\code\read
λ python -i test_write.py
>>> s = 'hello'
>>> s.upper()
'HELLO'
>>>
>>> f
<_io.TextIOWrapper name='out.txt' mode='w' encoding='cp1252'>
>>>
>>> # As long as interpreter is running it will not write
Now noting get written,i have to close interpreter first.
>>> exit() # Only now will it write to file

C:\code\read
with open has been the preferred way since it come out in Python 2.5.
Reply
#6
The question is, whether it is guaranteed to write when exit() is called (or earlier).
Reply
#7
(Oct-18-2019, 11:21 PM)kryptomatrix Wrote: The question is, whether it is guaranteed to write when exit() is called (or earlier).
No it's not guaranteed at all,it will fail in many cases as eg trying running in editors and not command line.
If i test in my editors will not write to file,dot not matter if i use exit() or close down the editor.
As long as the file object is open and not used it can be garbage collected.

To be sure has to use close().
f = open("out.txt", "w")
f.write("abc\n")
f.close()
Or better.
with open("out.txt", "w") as f:
    f.write("abc\n")
Reply
#8
(Oct-18-2019, 01:39 PM)perfringo Wrote:
(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 Smile.

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.

(Oct-18-2019, 11:44 PM)snippsat Wrote:
(Oct-18-2019, 11:21 PM)kryptomatrix Wrote: The question is, whether it is guaranteed to write when exit() is called (or earlier).
No it's not guaranteed at all,it will fail in many cases as eg trying running in editors and not command line.
If i test in my editors will not write to file,dot not matter if i use exit() or close down the editor.
As long as the file object is open and not used it can be garbage collected.

To be sure has to use close().
f = open("out.txt", "w")
f.write("abc\n")
f.close()
Or better.
with open("out.txt", "w") as f:
    f.write("abc\n")
Thank you. The standard is phrased a bit ambiguously.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python openyxl not updating Excel file MrBean12 1 250 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  Python logging RotatingFileHandler writes to random file after the first log rotation rawatg 0 341 Feb-15-2024, 11:15 AM
Last Post: rawatg
  Last record in file doesn't write to newline gonksoup 3 365 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  connect sql by python using txt. file dawid294 2 382 Jan-12-2024, 08:54 PM
Last Post: deanhystad
  file open "file not found error" shanoger 8 946 Dec-14-2023, 08:03 AM
Last Post: shanoger
  write to csv file problem jacksfrustration 11 1,374 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,314 Nov-09-2023, 10:56 AM
Last Post: mg24
  Replace a text/word in docx file using Python Devan 4 2,857 Oct-17-2023, 06:03 PM
Last Post: Devan
  Help creating shell scrip for python file marciokoko 10 1,258 Sep-16-2023, 09:46 PM
Last Post: snippsat
  Need to replace a string with a file (HTML file) tester_V 1 699 Aug-30-2023, 03:42 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020