So i am trying to get this done, the script executes every 5 minutes and the variable (a & b) changes with it, first time the script executes the file write the value but next time when it runs it overwrites the previous data.I want it to write the value of (a & b) in next row with overwriting the previous data. Tried using newline='' but got error.
import csv
a = 1
b = 4
#newline=''
with open('data.csv', mode='w') as data:
datawriter = csv.writer(data, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
datawriter.writerow([a,b])
Is there any easy fix where i can achieve it fast
data it has:
A B
1 6
Result i want when every time it runs:
A B
1 6
4 7
6 2
3 9
Any help would be appreciated
import csv
a = 1
b = 4
#newline=''
with open('data.csv', mode='a') as data:
datawriter = csv.writer(data, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
datawriter.writerow([a,b])
just change mode='a'
w
means write, a
means append, use append instead of write.
Check out the doc regarding file opening modes: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
In summary w
mode will always (over)write. You want to use a
to append new data to your file.
In your code you will need to check whether file exist, then choose the appropriate mode.
Open your file in a+
mode. This means appending. w
stands for write which means each time the document is opened the values are overwritten. Add time.sleep(300)
to have time intervals of 5 minutes.
import csv
import time
a = 1
b = 4
while True:
with open("data.csv", 'a+', newline='') as data:
datawriter = csv.writer(data, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
datawriter.writerow([a,b])
print("Round Done")
time.sleep(300)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.