你能帮我检查一下我的python代码是否正确,可以通过raspberry pi3以csv格式保存数据吗?
print("Gyro: %f, %f, %f [deg/s]" % (cgx, cgy, cgz))
print("Accel: %f, %f, %f [Gs]" % (cax, cay, caz))
print("Mag: %f, %f, %f [gauss]" % (cmx, cmy, cmz))
file = open("/home/pi/data_log.csv", "a")
if os.stat("/home/pi/data_log.csv").st_size == 0:
file.write("Time,Gyro,Accel,Mag\n")
while True:
now = datetime.now())
print >>f,("%s,%f,%f,%f,%f,%f,%f,%f,%f"%(now.datetime("%Y-%m-%d %H:%M:%S"),cgx,cgy,cgz,cax,cay,caz,cmx,cmy,cgz))
file.flush()
time.sleep(5)
file.close()
答案 0 :(得分:1)
以下类型的方法可以帮助您入门。您虽然缺少更新变量的代码,但目前它会导致每5秒写入相同的值:
from datetime import datetime
import csv
import os
print("Gyro: {}, {}, {} [deg/s]".format(cgx, cgy, cgz))
print("Accel: {}, {}, {} [Gs]".format(cax, cay, caz))
print("Mag: {}, {}, {} [gauss]".format(cmx, cmy, cmz))
filename = "/home/pi/data_log.csv"
write_header = not os.path.exists(filename) or os.stat(filename).st_size == 0
with open(filename, "a", newline="") as f_output:
csv_output = csv.writer(f_output)
if write_header:
csv_output.writerow(["Time", "Gyro", "Accel", "Mag"])
while True:
row = [datetime.now().strftime("%Y-%m-%d %H:%M:%S"), cgx, cgy, cgz, cax, cay, caz, cmx, cmy, cgz]
csv_output.writerow(row)
time.sleep(5)
Python的CSV库可用于将值列表转换为自动正确分隔的行。默认情况下,分隔符是逗号。