1

I would like to code a python that adds every x seconds a value. But when I add the time.sleep(x) theres no output into the .txt file anymore.

And is there a way to stop the loop after a certain time?

Code:

f = open('Log.txt','a')
while True:
    print("This prints once a second.", file=f)
    time.sleep(1)
julrie
  • 13
  • 3
  • Recursively append text to file with the print and sleep functions: ``` import time num = 1 def append_recursive(): with open('Log.txt', 'a') as f: print(f"This prints once every {num} second.", file=f) time.sleep(num) append_recursive() append_recursive() ``` Results in the file content of "Log.txt": ``` This prints once every 1 second. This prints once every 1 second. This prints once every 1 second. This prints once every 1 second. This prints once every 1 second. This prints once every 1 second. ``` – Gustav Rasmussen Jun 11 '20 at 12:52

2 Answers2

0

It is best to use a context manager, and this works:

import time

while True:
    with open('Log.txt','a') as f:
        print("This prints once a second.",file=f)
    time.sleep(1)
Red
  • 26,798
  • 7
  • 36
  • 58
0

Maybe something like this:

import time
while True:
    with open('Log.txt','a') as f:
        f.write("This prints once a second.\n")
    time.sleep(1)

If you want to stop after a given time:

import time
stop_after = 10 # seconds
start = time.time()

while time.time() - start < stop_after:
    with open('Log.txt','a') as f:
        f.write("This prints once a second.\n")
    time.sleep(1)
PApostol
  • 2,152
  • 2
  • 11
  • 21