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')嘗試....'? –