Search code examples
pythonraspberry-pigpio

Why doesn't my script write content to the file?


I wrote a script in Python which once I execute it and press a button connected to a GPIO on my Raspberry Pi should:

  • Print 'it works!'
  • Create a file named 'it_works.txt' with the content 'yay!'

The script does print 'it works!' and creates the file, but the content is missing once I open it. This is the script:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import RPi.GPIO as GPIO

# SET GPIO Button-Pin
gpio = 9

# Main Function
def main():
  value = 0

  while True:

    if not GPIO.input(gpio):
      value += 0.01

    if value > 0:

     if GPIO.input(gpio):
       print "it works!"
       with open("it_works.txt", "w") as file:
           file.write("yay!")
           main()

     time.sleep(0.03)

  return 0

if __name__ == '__main__':
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpio, GPIO.IN)
main()

I'm not experienced with Python, so I can't really say if I wrote something wrong. Any help would be appreciated, thanks a lot!


Solution

  • With the current yìcode you provide, you set up correctly the pin of the GPIO and then your main enters in a loop where it continues to open a file in 'write' mode, but you never close it properly. Add the file.close() line after the with declaration:

    with open("it_works.txt", "w") as file:

        file.write("yay!")
    
        main()
    

    file.close()

    (CARE FOR INDENTATION)

    Furthermore when you open a file in python with 'w' option it will truncate the content of the file. I don't know if this is relevant for you. I would suggest 'r+' or 'a'