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() ?
#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


Messages In This Thread
RE: Does python guarantees that file.write() works without file.close() ? - by kryptomatrix - Oct-21-2019, 11:28 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Delete file with read-only permission, but write permission to parent folder cubei 6 22,127 Jun-01-2024, 07:22 AM
Last Post: Eleanorreo
  Cannot get cmd to print Python file Schauster 11 594 May-16-2024, 04:40 PM
Last Post: xMaxrayx
  What does .flush do? How can I change this to write to the file? Pedroski55 3 386 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Python openyxl not updating Excel file MrBean12 1 448 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  Python logging RotatingFileHandler writes to random file after the first log rotation rawatg 0 499 Feb-15-2024, 11:15 AM
Last Post: rawatg
  Last record in file doesn't write to newline gonksoup 3 550 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  connect sql by python using txt. file dawid294 2 549 Jan-12-2024, 08:54 PM
Last Post: deanhystad
  file open "file not found error" shanoger 8 1,404 Dec-14-2023, 08:03 AM
Last Post: shanoger
  write to csv file problem jacksfrustration 11 1,788 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,736 Nov-09-2023, 10:56 AM
Last Post: mg24

Forum Jump:

User Panel Messages

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