You want to log sensor data every minute on your Raspberry Pi into a CSV file without losing old data. Which Python code snippet correctly achieves this?
hard📝 Best Practice Q15 of 15
Raspberry Pi - Data Logging and Databases
You want to log sensor data every minute on your Raspberry Pi into a CSV file without losing old data. Which Python code snippet correctly achieves this?
Aimport csv
with open('sensor_log.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow(['12:01', '32'])
Bimport csv
with open('sensor_log.csv', 'x', newline='') as f:
writer = csv.writer(f)
writer.writerow(['12:03', '33'])
Cimport csv
with open('sensor_log.csv', 'r') as f:
writer = csv.writer(f)
writer.writerow(['12:02', '31'])
Dimport csv
with open('sensor_log.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Time', 'Value'])
writer.writerow(['12:00', '30'])
Step-by-Step Solution
Solution:
Step 1: Identify file mode to keep old data
Mode 'a' appends new data without erasing existing logs, perfect for ongoing logging.
Step 2: Check code correctness for logging new data
Code opens file in append mode with newline='', writes one new row with time and value.
Final Answer:
Code that appends new rows without deleting old data -> Option A
Quick Check:
Append mode + newline='' = safe logging [OK]
Quick Trick:Use 'a' mode and newline='' to add logs safely [OK]
Common Mistakes:
MISTAKES
Using 'w' mode which erases old logs
Using 'r' mode which is read-only
Using 'x' mode which fails if file exists
Master "Data Logging and Databases" in Raspberry Pi
9 interactive learning modes - each teaches the same concept differently