1

I have this code which I am running on jupyter notebook

with open('tracker.txt', 'w+') as p:
    for i in range(1,100000000):
        p.write("\nValue is: "+str(i) )

while running this code when I am opening the tracker.txt file it is showing my blank, and only showing the result after the code is executed completely. But I want to see the results getting printed in the file in real time so that I can track the progress of the code. I am not able to get how to achieve that. Any help will be great.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Turing101
  • 347
  • 3
  • 15
  • 2
    Call `p.flush()` after `p.write(...)` inside the loop. – Stef Feb 21 '23 at 20:00
  • 1
    See also: [How often does python flush to a file?](https://stackoverflow.com/questions/3167494/how-often-does-python-flush-to-a-file) – Stef Feb 21 '23 at 20:00
  • Take a copy of your output file. It will show you where things are at. – JonSG Feb 21 '23 at 20:01

1 Answers1

1

Call p.flush() after p.write(...) inside the loop.

with open('tracker.txt', 'w+') as p:
    for i in range(1,100000000):
        p.write("\nValue is: {}".format(i) )
        p.flush()

See also: How often does python flush to a file?

Stef
  • 13,242
  • 2
  • 17
  • 28