好吧,所以我正在研究一个脚本,该脚本通过.txt
文件进行解析,并根据在文件中找到的某些字符串提出一些建议。
假设我要通过parameters.txt
文件进行解析,该文件如下所示:
ztta/roll_memory = 250000
shm = 5000
现在,我用于执行此操作的代码是:
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")
这里的问题是,如果.txt
文件中的参数之一的值如下:
ztta/roll_memory = 2500 (**instead of 250000**), the if statement would still be triggered.
谢谢
答案 0 :(得分:1)
放置if a in data
的另一种方法是:
if 'ztta/roll_memory = 250000' in 'ztta/roll_memory = 250000':
您会看到比较字符串中包含的子字符串a
,
不管尾随多少零。
另一种放置方式:
if 'ab' in 'abc' # True
if 'ab' in 'abd' # True
if 'hello00' in 'hello00000' # True
顺便说一句,您的代码不可扩展。您应该尝试以ints
而不是字符串的形式读取参数。即
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))