Bird
0
0

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:
  1. Step 1: Identify file mode to keep old data

    Mode 'a' appends new data without erasing existing logs, perfect for ongoing logging.
  2. 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.
  3. Final Answer:

    Code that appends new rows without deleting old data -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes