Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to continuously print a live timestamp to a csv file with Python?

I have this code, which looks for a specific image continously. If it sees the image, I want it to write "Duck" followed by the current datetime into a csv file:

now = datetime.datetime.now()

i = 1

f = open('ducklog.csv', 'a', newline=(''))
tup1 = ('Duck', now)
writer = csv.writer(f)



while i<=5:
    Got_him = pyautogui.locateCenterOnScreen("That Duck.png")
    if Got_him == None:
    print (Got_him)
    continue

else:
    now = datetime.datetime.now()
    print(Got_him)
    print("OH GOD THERE HE IS")
    print(now)
    writer.writerow(tup1)
    time.sleep(5)
    continue

This runs fine, but the issue I’m finding is that once the code finishes, it writes all of the lines to the csv simultaneously which means they all receive the same datetime value.

How can I have the datetime written into the csv iteratively, so that the times refect each individual datetime value that reflects when the image was actually seen?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Apart from the indentation in your code, the issue is that you set tup1 once at the beginning, rather than feeding it the time at which you find the duck. Changing now later on, will not update the value in the tuple.

Within your else block, you either have to update tup1 giving it the new value for now or you get rid of tup1 altogether:

...
now = datetime.datetime.now()  
tup1 = ('Duck',now)  
writer.writerow(tup1)

or (in my opinion more readable)

...
writer.writerow(('Duck', datetime.datetime.now()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading