Reputation: 11
I am trying to access the content of a file while that file is still being updated. Following is my code that does the writing to file job:
for i in range(100000):
fp = open("text.txt", "w")
fp.write(str(i))
fp.close()
#time.sleep(1)
My problem now is that whenever I try to open my file while the for loop is still running, I get an empty file in text editor(I except to see an "updated" number). I am wondering is there a way that allows me to view the content of file before the for loop ends?
Thanks in advance for any help: )
Upvotes: 1
Views: 76
Reputation: 2597
Do not open file inside for loop. It is a bad practice and bad code. Each and every time you create a new object. That is why you get an empty file.
fp = open("text.txt", "r+")
for i in range(100000):
fp.seek(0)
fp.write(str(i))
fp.truncate()
fp.close()
Upvotes: 4
Reputation: 3945
When you write to a file it usually does not actually get written to disk until file is closed. If you want it to be written immediately you need to add a flush
to each iteration, hence:
fp = open("text.txt", "w")
for i in range(100000):
fp.write(str(i))
fp.write("\n")
fp.flush()
fp.close()
Upvotes: 0
Reputation: 57033
Modern operating systems buffer file writes to improve performance: several consecutive writes are lumped together before they are actually written to the disc. If you want the writes to propagate to the disk immediately, use method flush()
, but remember that it drastically reduces application performance:
with open("text.txt", "w") as fp:
for i in range(100000):
fp.write(str(i))
fp.flush()
Upvotes: 2