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?
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()))