0

so I've set up a potentiometer and an LED and a section of the code is below:

        while True:
            if (GPIO.input(22) == GPIO.HIGH):
                now = str(datetime.now())
                text_file = open("button.txt", "w")
                text_file.write("\n switch activated at " + now)
                text_file.close()
                print("switch activated at" + now)
            while GPIO.input(22) == GPIO.HIGH:
                GPIO.output(4, GPIO.HIGH)
            else:
                GPIO.output(4, GPIO.LOW)

IT works well, and the LED turns on when the pot is activated and turns off when it's deactivated. Except it only saves the time for the last that the potentiometer is activated, can i do anything to fix this? This is my first time trying to save things to a .txt file so please be lenient.

2 Answers2

0

When you open a file with "w" it will erase everything in the file and just save the new information.

You want to open a file for appending with "a", like such:

text_file = open("button.txt", "a")

From the Input and Output documentation:

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.

Jezzamon
  • 1,453
  • 1
  • 15
  • 27
0

The "w" in the open function specifies to overwrite the file with what you write. Use "a" to append.

      while True:
        if (GPIO.input(22) == GPIO.HIGH):
            now = str(datetime.now())
            text_file = open("button.txt", "a")
            text_file.write("\n switch activated at " + now)
            text_file.close()
            print("switch activated at" + now)
        while GPIO.input(22) == GPIO.HIGH:
            GPIO.output(4, GPIO.HIGH)
        else:
            GPIO.output(4, GPIO.LOW)

For more info on these parameters check out this answer.

Community
  • 1
  • 1
John Howard
  • 61,037
  • 23
  • 50
  • 66