I have been trying to make python code that reads a text file makes it a variable and sends it using i2c. Heres the code:
import serial
import smbus
import time
import sys
from time import sleep
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)
# This is the address we setup in the Arduino Program
address = 0x04
loopvar = 1
while loopvar == 1:
text_file = open("./PB_Vision/command.txt", "r")
print text_file.read()
visioncommando = text_file.read()
print visioncommando
def writeNumber(value):
bus.write_byte(address, value)
bus.write_byte_data(address, 0, value)
return -1
var = int(visioncommando)
writeNumber(var)
print ("RPI: Hi Arduino, I sent you")
print (var)
text_file.close()
when I run this, I get this as output;
110
Traceback (most recent call last):
File "testai.py", line 29, in <module>
var = int(visioncommando)
ValueError: invalid literal for int() with base 10: ''
any suggestion, fixes?
anyways thanks in advance.
Thanks your suggestions worked, one step closer to an working project.
if your command.txt file contains:
110
Then the following code is wrong:
while loopvar == 1:
text_file = open("./PB_Vision/command.txt", "r")
print text_file.read()
visioncommando = text_file.read()
print visioncommando
Your 2nd text_file.read() call will result in "" (en empty string) because you've already exhausted the contents of the open file object.
You could do something liket his instead:
while loopvar == 1:
text_file = open("./PB_Vision/command.txt", "r")
visioncommando = text_file.read()
print visioncommando
Remove this:
print text_file.read()
and it will work.
Iterators can only be used once...
You read the file in the wrong way, python convert 110 to int but it find an empty string '' after that. So I would suggest to add a condition before int() command and str.isdigit() is a good candidate.
Related
So in my program im attempting to search a document called console.log that has lines like this:
65536:KONSOLL:1622118174:NSN:ActivationUnits::HandleActivationUnitsMessages. There is no handler for FNo: 34
65536:KONSOLL:1622177574:NSN:ActivationUnits::HandleActivationUnitsMessages. There is no handler for FNo: 34
65536:KONSOLL:1622190642:NSN:From AutroSafe: 28 5 2021, 08:30:42; 05.046; Service: "Self Verify" mislykket; ; ; ProcessMsg; F:2177 L:655; 53298;1;13056;;
65536:KONSOLL:1622204573:NSN:ActivationUnits::HandleActivationUnitsMessages. There is no handler for FNo: 34
In my input i always specify "Self Verify" as im looking after that. I want the detectornumber (05.046) on the output. But i get a error.
This is my code:
import os
import re
pattern = input("What are you searching for? -->")
detectorPattern = re.compile(r'\d\d.\d\d\d')
directory = os.listdir()
for x in range(len(directory)):
with open(directory[x], 'r') as reader:
print("Opening " + directory[1])
# Read and print the entire file line by line
for line in reader:
findLine = re.search(pattern, line)
if findLine is not None:
mo = detectorPattern.search(findLine)
print(mo.group())
So what im trying to do is to to go for one line, and if i find "Self Verify" i will search that line for the detector specified in detectorPattern, and print that one out.
This is the error i get:
Traceback (most recent call last):
File "C:\Users\haral\Desktop\PP\SVFinder.py", line 14, in <module>
mo = detectorPattern.search(findLine)
TypeError: expected string or bytes-like object
Change:
mo = detectorPattern.search(findLine)
To:
mo = detectorPattern.search(findLine.string)
This will print:
162219
when executing the line:
print(mo.group())
I suggest you put directly line into detectorPattern.search.
Also please not if x is not None: can be replaced by if x:
This example should works as is:
import re
pattern = "Self Verify"
reader = ['65536:KONSOLL:1622118174:NSN:ActivationUnits::HandleActivationUnitsMessages. There is no handler for FNo: 34',
'65536:KONSOLL:1622177574:NSN:ActivationUnits::HandleActivationUnitsMessages. There is no handler for FNo: 34',
'65536:KONSOLL:1622190642:NSN:From AutroSafe: 28 5 2021, 08:30:42; 05.046; Service: "Self Verify" mislykket; ; ; ProcessMsg; F:2177 L:655; 53298;1;13056;; ',
'65536:KONSOLL:1622204573:NSN:ActivationUnits::HandleActivationUnitsMessages. There is no handler for FNo: 34]']
for line in reader:
findLine = re.search(pattern, line)
detectorPattern = re.compile(r'\d\d.\d\d\d')
if findLine:
detector = detectorPattern.search(line).group()
print(detector)
Output:
162219
I want the detectornumber (05.046) on the output
This seems to do the job. I just changed findLine by pattern in detectorPattern.
import os
import re
pattern = input("What are you searching for? -->")
detectorPattern = re.compile(r'\d\d.\d\d\d')
directory = os.listdir()
for x in range(len(directory)):
with open(directory[x], 'r') as reader:
print("Opening " + directory[1])
# Read and print the entire file line by line
for line in reader:
findLine = re.search(pattern, line)
if findLine is not None:
mo = detectorPattern.search(pattern)
print(mo.group())
I would like the bots.txt to be read as an int instead of an str. However none of the videos i find on the internet help, or go into major detail on how I can solve this issue.
Here is my code
import time
import os
import random
os.system('mode 88,30')
with open('B://JakraG2//.Bots//bots.txt', 'r') as f:
aaa = f.read()
counter = aaa
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
lel = "{}".format(counter)
with open('B://JakraG2//.Bots//bots.txt', 'w') as f:
f.write("{}".format(lel))
Here is the error
Traceback (most recent call last):
File "loader.py", line 16, in <module>
counter = counter + 1
TypeError: can only concatenate str (not "int") to str
bots.txt
0
When you read from a file with f.read, the information acquired is determined as a string, which is why when you try to add 1 to counter ( f.e 5 + 1), the program thinks you are trying to do something like this "5" + 1.
A simple fix would be to state that what you read from the file is an integer:
aaa = int(float(f.read()))
File when read are always strings - you need to convert to integer to use integer addition.
import time
# read file
try:
with open('bots.txt', 'r') as f: # you use B://JakraG2//.Bots//bots.txt'
aaa = f.read().strip()
counter = int(aaa)
except Exception as e:
print(e) # for informational purposes when testing
counter = 0 # f.e. file not exists or invalid text2number in it
while True:
time.sleep(0.05)
print("Added 1 to bots.txt")
counter = counter + 1
# overwrites existing file
with open('bots.txt', 'w') as f: # you use B://JakraG2//.Bots//bots.txt'
f.write(f"{counter}")
I have a json file out of which one field has list data as shown below
{
"broker_address":"0.0.0.0",
"serial_id": "YYMMSSSSSSVV",
"auto_foc": true,
"timer": [0,23,30]
}
I am taking user input for timer field so I want to replace the timer data with the input value received from user. On trying it I am getting following error
Traceback (most recent call last):
File "test.py", line 23, in <module>
time, final)
TypeError: Can't convert 'list' object to str implicitly
My code snippet is as follows
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
az = filer.read()
print(az)
read_file = az.rstrip('/n')
data = json.loads(read_file)
#print("printing file",json.loads(read_file))
time=data["timer"]
#print(read_file)
print(time)
print("Waiting.....................")
#time.sleep(2)
final = str(val)
print(final)
read_file = read_file.replace(
time, final)
with open('/home/pi/config.json', 'w') as filer:
filer.write(read_file)
Please let me know how to resolve this error.
Try this:
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
az = filer.read()
print(az)
read_file = az.rstrip('/n')
data = json.loads(read_file)
#print("printing file",json.loads(read_file))
time=data["timer"]
#print(read_file)
print(time)
print("Waiting.....................")
#time.sleep(2)
final = str(val).split()
final = [int(i) for i in final]
print(final)
print(str(time))
read_file = read_file.replace(str(time), str(final))
print(read_file)
with open('/home/pi/config.json', 'w') as filer:
filer.write(read_file)
And update the json file from "timer": [0,23,30] to "timer": [0, 23, 30] i.e. add spaces
One thing avoid using the name time when you use that name as a variable it will replace the imported name time. Secondly the issue is that the data is a list not a string and replace is expecting a string not a list.
What you will want to do is just take advantage of json for what it is a serializer and deserializer and modify the data itself and use json to write it to a file. This also ensures you will be able to read it back out as json.
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
data = json.load(filer)
timer=data["timer"] #DONT USE time
print(timer)
print("Waiting.....................")
#time.sleep(2)
final = str(val)
print(final)
#This next part will be up to you,
# do you want this to be the list it was before?
# or the string as input
data['timer'] = final
with open('/home/pi/config.json', 'w') as filer:
json.dump(data,filer)
So I've seen this code;
with open(fname) as f:
content = f.readlines()
in another question. I just need some confirmation on how it works.
If I were to have a file named normaltrack.py which contains code;
wall 0 50 250 10
wall 0 -60 250 10
finish 200 -50 50 100
I should have a list called wall = [] and have the opening code as;
with open(normaltrack.py) as f:
wall = f.readlines()
to open the file and store the lines of code that start with "wall" into the list?
Do I always have the change the "fname" everytime I want to open a different file? Or is there a way to do it from the interpreter? Such as python3 assignment.py < normaltrack.py ?
In your example:
with open(fname) as f:
content = f.readlines()
'fname' is a variable reference to a string. This string is the file path (either relative or absolute).
To read your example file, and generate a list of all lines that with 'wall', you can do this:
fname = '/path/to/normaltrack-example.txt' # this would be an absolute file path in Linux/Unix/Mac
wall = []
with open(fname) as the_file:
for line in the_file:
if line.startswith('wall'):
wall.append(line) # or wall.append(line.rstrip()) to remove the line return character
In general, it's best to not call 'readlines()' on a file object unless you control the file (that is, it's not something the user provides). This is because readlines will read the entire file into memory, which sucks when the file is multiple GBs.
Here's a quick and dirty script that does what you want.
import sys
if len(sys.argv) > 1:
infile = sys.argv[1]
else:
print("Usage: {} <infile>".format(sys.argv[0]))
sys.exit(1)
with open(infile, 'r') as f:
walls = []
for line in f:
if line.startswith('wall'):
walls.append(line.strip())
If you name this script 'read_walls.py', you can run it from the command line like this,
python read_walls.py normaltrack.py
Ordinarily, I'd use argparse to parse command-line arguments, and write a main() function for the code. (That makes it testable in the interactive python interpreter.)
this code should work for you
#!/usr/bin/env python
import sys
def read_file(fname):
call = []
with file(fname) as f:
call = f.readlines()
call = filter(lambda l: l.startswith('wall'), call)
return call
if __name__ == '__main__':
fname = sys.argv[1]
call = read_file(fname)
print call
I am trying to insert a file and I keep getting a syntax error on the line line = infile.redline()
def main():
# Declare variables
line = ''
counter = 0
# Prompt for file name
fileName = input('Enter the name of the file: ')
# Open the specified file for reading
infile = open('test.txt', 'r')
# Priming read
line = infile.redline()
counter = 1
# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '\n'
line = line.rtrip('\n')
print(line)
1ine = infile.readline()
# Update counter when line is read
counter +=1
# Close file
infile.close()
# Call the main function.
main()
rtrip should be rstrip. redline should be readline. infile.close() should be indented, and main() should not be.
However, the most serious problem is here:
1ine = infile.readline()
That first character is a one, not an L.
Knowing the standard libraries can make your life much simpler!
from itertools import islice
def main():
fname = input('Enter the name of the file: ')
with open(fname) as inf:
for line in islice(inf, 5): # get the first 5 lines
print(line.rstrip())
if __name__=="__main__":
main()
It is not redline but readline:
line = infile.redline()