1

I opened two command prompts and started python 3.7 interpreters in both. I could open the same file on both prompts, I could also close them interchangeably, I figured that whenever I use write() to write to a file it actually write to buffer and then when the file is closed it writes whatever was in the buffer of that stream, overwriting data that was written with the previous stream. I don't understand how I didn't get any errors. Does anyone know what is happening internally?

Danilo Gacevic
  • 474
  • 3
  • 13

1 Answers1

0

When you open each of the files (in 'w' mode), each of the file objects are pointing at position 0 in the file. If you write 10 characters from one process, and then 5 characters from another process, the first 5 characters of the first write will be replaced by the second write. Try:

# shell 1                     # shell 2
f = open('test.txt', 'w')     f = open('test.txt', 'w')
f.write("a"*10)
                              f.write("b"*5)
f.close()                     
                              f.close()

the final file should be bbbbbaaaaa

As explained here, Python hands the buffering logic off to the file system unless you specify otherwise.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96