Reputation: 47
Ok, so I am working on a script that parses through a .txt
file and based on certain strings that it finds in the file, makes certain recommendations.
Let's say that I want to parse through the parameters.txt
file which looks something like:
ztta/roll_memory = 250000
shm = 5000
Now, the code I am using to do this is:
a = 'ztta/roll_memory = 250000'
b = 'shm = 5000'
with open('parameter.txt', 'r') as myfile:
data = myfile.read()
if a in data:
print("the value of ztta/roll_memory is correct --> PASS")
else:
print("the value of ztta/roll memory is incorrect --> FAIL")
if b in data:
print("the value of shm is correct --> PASS")
else:
print("the value of shm is incorrect --> FAIL")
The issue here is that if one of the parameters in the .txt
file would have a value like:
ztta/roll_memory = 2500 (**instead of 250000**), the if statement would still be triggered.
Thank you
Upvotes: 0
Views: 54
Reputation: 1229
Another way of putting if a in data
is:
if 'ztta/roll_memory = 250000' in 'ztta/roll_memory = 250000':
You can see that the substring a
in enclosed in the comparative string,
regardless of how many zeros trail it.
Another way of putting it:
if 'ab' in 'abc' # True
if 'ab' in 'abd' # True
if 'hello00' in 'hello00000' # True
On an aside, your code is not scalable. You should try reading in the parameters as ints
instead of strings. I.e.,
good_values = {'ztta/roll_memory': 250000, 'shm': 5000}
params = {}
with open('parameter.txt','r') as myfile:
for line in myfile:
line_array = [x.strip() for x in line.split('=')]
params[line_array[0]] = int(line_array[-1])
for key in params:
if params[key] == good_values[key]:
print("the value of {0} is correct --> PASS".format(key))
else:
print("the value of {0} is incorrect --> FAIL".format(key))
Upvotes: 1