raspberry pi - python read file to turn on LED -


i'm trying python script read contents of text file , if it's 21 turn on led if it's 20 turn off. script prints out contents of text file on screen.

the contents print out works ok led 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) 

print fh.read()  

reads entire contents of file, leaving file cursor @ end of file, when

line = fh.read() 

there's nothing left 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 code, since don't have raspberry pi, code ensure line contains entire contents of text file. might not desirable: if file contains any whitespace, eg blank spaces or newlines, if ... else tests won't behave want. can fix doing

line = line.strip()  

after line = fh.read()

the .strip method strips off leading or trailing whitespace. can pass argument tell strip, see the docs details.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -