Consider those two python programs:
script_a.py
:
from datetime import datetime
from time import sleep
while True:
sleep(1)
with
You are allowed to open a file as many times as you want, so long as the operating system doesn't stop you. This is occasionally useful to get multiple cursors into a file for complex operations.
The reason that script_b.py
thinks that the file is empty is that the file is empty:
with open('foo.txt', 'w') as f:
opening a file in w
mode immediately erases (i.e. truncates) the file. There's an initial three second gap in script_a
where the file is completely 100% empty, and that's what script_b
sees.
In the next three second gap after you call f.write
, the file is still... probably empty. This is due to buffering - the file on disk is not guaranteed to contain everything that you have written to it with write
until you either close
(i.e. exit the context manager block) or manually invoke flush
on the file handle.
Alternatively, you can open in unbuffered mode, so that writes are always immediately written to disk.
with open('foo.txt','w',0) as f:
#no buffering, f.write() writes immediately to disk