1
我正在寻找输入文件中以“ND”开头的行。 ,看起来像这样:查找输入文件中的确切字符串
ND 195 4.53434033e+006 5.62453069e+006 2.56369141e+002
ND 196 4.53436645e+006 5.62443565e+006 2.56452118e+002
NS 129 113 97 82 58 59 37 22 17 18
NS 5 6 12 26 42 64 62 85 102 117
我写了这样的代码:
from __future__ import print_function
found_ND = False
text = "ND"
with open('input.txt', 'r') as f, open('output.dat', 'w') as outfile:
for line in f:
if text in line:
found_ND = True
if found_ND:
#do whatever you want
try:
line = line.strip()
columns = line.split()
i = float(columns[1])
x = float(columns[2])
y = float(columns[3])
z = float(columns[4])
print(z)
print("{:.2f}".format(z), file=outfile)
except ValueError:
pass
但结果我得到的也开始与“NS”字符串的第四列。 结果是这样的:
256.37
256.45
82.00
26.00
我如何编写代码来避免开头的行"NS"
?
你的意思是'如果line.startswith('ND')尝试....'? –