1

Could you help me to check whether my python code below is correct for saving data in csv format via raspberry pi3?

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()
2
  • Think about whether you plan to hold the file open all the time, or open and close it on every iteration. Commented Nov 30, 2017 at 9:43
  • You are open()ing the file only once at the top, but close()ing it multiple times in the eternal loop. Also I don't understand the print >>f part. Commented Nov 30, 2017 at 11:41

1 Answer 1

1

The following type of approach should get you started. You are though missing code to update your variables, so at the moment it would result in the same values being written every 5 seconds:

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's CSV library can be used to convert a list of values into a row which is correctly delimited automatically. By default the delimiter is a comma.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.