Python Forum

Full Version: save data in .txt after certain interval
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Everyone,

Here is just snippet of my code to tell exact my requirement and not my actual code.

import time, datetime

ctr=100

opn = open("log.txt","a+")

while(ctr):
    opn.writelines(str(ctr))
    ctr=ctr-1
    time.sleep(1)
    print(ctr)

opn.close() #close file
I am working on automating a process in which I need to save the data after certain interval of time.
Above method works but data will store only after the file closes. Also, I can not get the data in file if user interrupt the process.

Is there any way I can save the log after every interval before "opn.close" instruction? Guide me if I am wrong as I already read the details of "OPEN" in Python manual

Thanks
Use the flush() method. Also your use of writelines is not correct
import time, datetime
 
ctr=100
 
opn = open("paillasse/ecrlog.txt","a+")
 
while(ctr):
    opn.write(str(ctr) + '\n')
    opn.flush()
    ctr=ctr-1
    time.sleep(1)
    print(ctr)
 
opn.close() #close file