3

I'm trying to get a python script to read the contents of a text file and if it's 21 turn on a LED but if it's 20 turn it off. The script also prints out the contents of the text file on the screen.

The contents print out works all ok but the LED does not turn on.

import wiringpi2
import time

wiringpi2.wiringPiSetupGpio()
wiringpi2.pinMode(17,1)

while 1:
    fh=open("test1.txt","r")
    print fh.read() 
    line = fh.read()
    fh.close()
    if line == "21":
        wiringpi2.digitalWrite(17,1)
    elif line == "20":
        wiringpi2.digitalWrite(17,0)
    time.sleep(2)
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182

1 Answers1

2
print fh.read() 

reads the entire contents of the file, leaving the file cursor at the end of the file, so when you do

line = fh.read()

there's nothing left to read.

Change this:

fh=open("test1.txt","r")
print fh.read() 
line = fh.read()
fh.close()

to this:

fh=open("test1.txt","r")
line = fh.read()
print line 
fh.close()

I can't test this code, since I don't have a Raspberry Pi, but that code will ensure that line contains the entire contents of the text file. That might not actually be desirable: if the file contains any whitespace, eg blank spaces or newlines, then your if ... else tests won't behave like you want. You can fix that by doing

line = line.strip() 

after line = fh.read()

The .strip method strips off any leading or trailing whitespace. You can also pass it an argument to tell it what to strip, see the docs for details.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182