python - writing into .csv-file inside of "while"-loop -
by using
result = open("data/"+ name + "_" + timestamp + ".csv", "w") result.write("time; data1; data2; data3 \n")`
i open file , fill column identifiers.
using
while true: timestamp = time.strftime("%h:%m:%s", time.localtime()) data1,data2,data3 = device.fetchdata() result.write(timestamp +";"+ str(data1) +";"+ str(data1) +";"+ str(data3) +"\n") time.sleep(seconds)
the .csv-file should filled measuring data. problem is, if check file after exiting script, it's completely empty, not column identifiers present. however, if use for-loop, works should.
very strange understanding.
i assume want leave program running indefinitely collect data kind of sensor, , suspect issue default buffering open() call.
firstly, should using "with" block @spirine suggests, in case slight modification in order:
with open("data/"+ name + "_" + timestamp + ".csv", "w", 1) result:
the , 1
@ end indicates line buffering, meaning python write file disk @ end of each line. also, consider using str.format() make bit more polished:
log_line_template = "{ts:%h:%m:%s};{d1};{d2};{d3}\n" filename = "data/{n}_{ts:%h_%m_%s}.csv".format(n=name, ts=datetime.now()) open(filename, "w", 1) result: result.write("time; data1; data2; data3 \n")` while true: data1,data2,data3 = device.fetchdata() result.write(log_line_template.format( ts=datetime.now(), data1, data2, data3 )) time.sleep(seconds)
Comments
Post a Comment