title: Sensor data log csv in python
body: <p>I am new to programming and want to write a code for an infrared sensor to log a timestamp in a .csv file whenever it detects motion. So far I have found code for the detection but now need to add code to specify for it to write an entry in a csv file. Credits for motion detection code: <a href="https://www.modmypi.com/blog/raspberry-pi-gpio-sensing-motion-detection" rel="nofollow">https://www.modmypi.com/blog/raspberry-pi-gpio-sensing-motion-detection</a></p>
  
  <pre><code>import RPi.GPIO as GPIO
  import time
  
  GPIO.setmode(GPIO.BCM)
  PIR_PIN = 7
  GPIO.setup(PIR_PIN, GPIO.IN)
  
  def MOTION(PIR_PIN):
  print ("Motion Detected")
  
  print ("PIR Module Test (CTRL+C to exit)")
  
  time.sleep(2)
  print ("Ready")
  
  try:
      GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
      while 1:
          time.sleep(100)
  
  except KeyboardInterrupt:
      print("Quit")
      GPIO.cleanup()
  </code></pre>
  
  <p>Next I am trying to add something along the following lines which will then write in two columns TIMESTAMP and "motion detected": </p>
  
  <pre><code>import csv
  import strftime 
  
  row = [strfttime("%a, %d %b %Y %H:%M:%S"), motion_detected]    
  with open('datalog.csv', 'a') as f:
      w = csv.writer(f)
      w.writerow(row)
  </code></pre>
  
  <p>I have only found ways to write to CSV's from static files so they didn't seem to provide a straightforward answer to my question. So any help in joining these codes or correcting the second would be great!</p>