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.
我正在尝试获取一个python脚本来读取文本文件的内容,如果它是21打开一个LED,但如果它是20关闭它。该脚本还会在屏幕上打印出文本文件的内容。
The contents print out works all ok but the LED does not turn on.
内容打印输出正常,但LED无法打开。
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)
1 个解决方案
#1
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
我无法测试此代码,因为我没有Raspberry Pi,但该代码将确保该行包含文本文件的全部内容。这可能实际上并不可取:如果文件包含任何空格,例如空格或换行符,那么if ... else测试将不会像您想要的那样运行。你可以通过这样做来解决
line = line.strip()
after line = fh.read()
在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.
.strip方法剥离任何前导或尾随空格。您也可以传递一个参数来告诉它要剥离的内容,请参阅文档了解详细信息。
#1
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
我无法测试此代码,因为我没有Raspberry Pi,但该代码将确保该行包含文本文件的全部内容。这可能实际上并不可取:如果文件包含任何空格,例如空格或换行符,那么if ... else测试将不会像您想要的那样运行。你可以通过这样做来解决
line = line.strip()
after line = fh.read()
在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.
.strip方法剥离任何前导或尾随空格。您也可以传递一个参数来告诉它要剥离的内容,请参阅文档了解详细信息。