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)
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.
Related
Please help I need python to compare text line(s) to words like this.
with open('textfile', 'r') as f:
contents = f.readlines()
print(f_contents)
if f_contents=="a":
print("text")
I also would need it to, read a certain line, and compare that line. But when I run this program it does not do anything no error messages, nor does it print text. Also
How do you get python to write in just line 1? When I try to do it for some reason, it combines both words together can someone help thank you!
what is f_contents it's supposed to be just print(contents)after reading in each line and storing it to contents. Hope that helps :)
An example of reading a file content:
with open("criticaldocuments.txt", "r") as f:
for line in f:
print(line)
#prints all the lines in this file
#allows the user to iterate over the file line by line
OR what you want is something like this using readlines():
with open("criticaldocuments.txt", "r") as f:
contents = f.readlines()
#readlines() will store each and every line into var contents
if contents == None:
print("No lines were stored, file execution failed most likely")
elif contents == "Password is Password":
print("We cracked it")
else:
print(contents)
# this returns all the lines if no matches
Note:
contents = f.readlines()
Can be done like this too:
for line in f.readlines():
#this eliminates the ambiguity of what 'contents' is doing
#and you could work through the rest of the code the same way except
#replace the contents with 'line'.
I try to found on google but was useless... I use pycharm and I want to print file lines with ascii white space like "\n", "\t", "\r", etc. but all I get is just the normal string like I see it with any text editor but I want to see and that characters to to know how to reproduce that text file for some personal projects.
I do not what to make them by my self so I want to shoe them on console and to just copy-paste them.
Thanks in advance.
# Local variable
fileName = r"C:\Users\...\textFile.txt"
# Create .mcmeta file
def mcmetaMaker(fileName=fileName):
try:
with open(file=fileName, mode="r", encoding="utf-8") as f:
line = f.readline()
while line:
print("\b{}".format(line))
line = f.readline()
finally:
f.close()
# Local variable
fileName = r"C:\Users\...\textFile.txt"
# Create .mcmeta file
def mcmetaMaker(fileName):
try:
with open(fileName, mode='rb') as f:
line = f.readline()
while line:
betterline = str(line)
print(betterline[2:len(betterline)-1])
line = f.readline()
finally:
f.close()
This worked for me. The 'b' in 'rb' stands for binary mode, which doesn't change the original bytes of the string.
print(line) produces b'asdf\r\n' so I converted it to string and sliced it. Hope it doesn't run too slow this way.
def codeOnly (file):
'''Opens a file and prints the content excluding anything with a hash in it'''
f = open('boring.txt','r')
codecontent = f.read()
print(codecontent)
codeOnly('boring.txt')
I want to open this file and print the contents of it however i don't want to print any lines with hashes in them. Is there a function to prevent these lines from being printed?
The following script with print all lines which do not contain a #:
def codeOnly(file):
'''Opens a file and prints the content excluding anything with a hash in it'''
with open(file, 'r') as f_input:
for line in f_input:
if '#' not in line:
print(line, end='')
codeOnly('boring.txt')
Using with will ensure that the file is automatically closed afterwards.
You can check if the line contains a hash with not '#' in codecontent (using in):
def codeOnly (file):
'''Opens a file and prints the content excluding anything with a hash in it'''
f = open('boring.txt','r')
for line in f:
if not '#' in line:
print(line)
codeOnly('boring.txt')
If you really want to keep only code lines, you might want to keep the part of the line until the hash, because in languages such as python you could have code before the hash, for example:
print("test") # comments
You can find the index
for line in f:
try:
i = line.index('#')
line = line[:i]
except ValueError:
pass # don't change line
Now each of your lines will contain no text from and including the hash tag until the end of the line. Hash tags in the first position of a line will result in an empty string, you might want to handle that.
Consider the following python script
#test.py
import sys
inputfile=sys.argv[1]
with open(inputfile,'r') as f:
for line in f.readlines():
print line
with open(inputfile,'r') as f:
for line in f.readlines():
print line
Now I want to run test.py on a substituted process, e.g.,
python test.py <( cat file | head -10)
It seems the second f.readlines returns empty. Why is that and is there a way to do it without having to specify two input files?
Why is that.
Process substitution works by creating a named pipe. So all the data consumed at the first open/read loop.
Is there a way to do it without having to specify two input files.
How about buffering the data before using it.
Here is a sample code
import sys
import StringIO
inputfile=sys.argv[1]
buffer = StringIO.StringIO()
# buffering
with open(inputfile, 'r') as f:
buffer.write(f.read())
# use it
buffer.seek(0)
for line in buffer:
print line
# use it again
buffer.seek(0)
for line in buffer:
print line
readlines() will read all available lines from the input at once. This is why the second call returns nothing because there is nothing left to read. You can assign the result of readlines() to a local variable and use it as many times as you want:
import sys
inputfile=sys.argv[1]
with open(inputfile,'r') as f:
lines = f.readlines()
for line in lines:
print line
#use it again
for line in lines:
print line
Here is my script:
def tail(file, delay=0.5):
f = open(file, 'r')
f.seek(0, 2)
while True:
line = f.readline()
print 'line: ' + line
if not line:
time.sleep(delay)
else:
print 'line found!'
When i open the file and add some lines to it, this script is not picking it up. I am doing this on linux.
use open('filename', 'a') instead of open('filename', 'r') for adding lines to the file ... I think you actually want to append to the file rather than reading it.
The code looks fine so there is likely a buffering issue. Try using f.read(100) instead of readline so that you read whatever is available rather than searching for line endings.