I have some code (shown below) which turns the Raspberry Pi into a datalogger. I use GPIO.add_event_detect to detect the date and time that a square wave signal changes state. This data is then saved to a CSV file continuously as each state change is detected. However if I turn the Raspberry Pi off or stop the program from running, when I then turn it back on again the previous CSV file is overwritten by a new file. Does anyone know how I could create a new CSV file every time I reboot the program/Pi?

import RPi.GPIO as GPIO
import datetime
from datetime import timedelta
import time
from time import sleep
import csv
from csv import writer

# endTime = datetime.datetime.now() + datetime.timedelta(seconds=60)

def my_callback(channel):
     data_writer([GPIO.input(40), datetime.datetime.now()])      # writes the detected
     # edge event to a CSV file with columns of rise/fall and the date & time of detection

if __name__ == '__main__':

    GPIO.setmode(GPIO.BOARD)       # set up GPIO numbering (BOARD = physical pins on Pi)
    GPIO.setup(40, GPIO.IN)         # set physical pin 40 as input

# create CSV file to write edge detection data to called Datalogger, with data on new line
    with open('/media/pi/KINGSTON/datalogger.csv', 'w', newline='') as Datalogger:
        data_writer = writer(Datalogger)

        data_writer.writerow(["Edge type", "Date & Time"])       # create headers in CSV file

        GPIO.add_event_detect(40, GPIO.BOTH, callback=my_callback)     # edge detection function
        # detects both rise and fall in signal on pin 40, then runs my callback

        while True:
# main program loop here - loops detection of edges then runs my callback
          # if datetime.datetime.now() >= endTime:
              # break
              # exit()

You need to open the file in append mode, not overwrite mode.

Change the mode in the open statement from w to a:

open('/media/pi/KINGSTON/datalogger.csv', 'a',  newline='')
| improve this answer | |
  • Thanks for your response. Would this just keep appending the very first CSV file I make? When I run my script it creates a CSV file and continuously populates it with data. However when I stop the script and then restart it, it overwrites the previous CSV file. I would like to keep the original CSV file but then create a new CSV file on every reboot. – user93154 Nov 1 '18 at 10:16
  • If you want a new file, then you should state that in the question. If you want a new file bot keep the old file, then the solution is to use a different file name. – RalfFriedl Nov 1 '18 at 10:18
  • Simplest way is to add the date and time to the filename. – CoderMike Nov 1 '18 at 10:22
  • Hi @Dan, if the answer help you, then you should accept it. – Ingo Nov 1 '18 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy