通过.txt文件进行分析时出现问题

2024-10-03 00:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我正在编写一个脚本,它通过.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.

谢谢


Tags: 文件oftheintxtdataifis
1条回答
网友
1楼 · 发布于 2024-10-03 00:18:20

另一种放置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))

相关问题 更多 >