2016-09-29 50 views
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"

+0

你的意思是'如果line.startswith('ND')尝试....'? –

回答

2

那么,您使用的是标志found_ND,使其True如果该行被发现(这恰好为第一行),然后永远不会更改回False

if text in line: 
    found_ND = True 

found_NDTrue适用于所有后续迭代。总之,就是不使用标志,你不需要它:

for line in f: 
    if text in line: 
     #do whatever you want 
     try: 
      line = line.strip() 
      columns = line.split() 
      # .. and so on. 

,或者,如果你严格要检查的开始(即行可能包含'ND'其他地方)使用startswith为@ Wiktor建议:

for line in f: 
    if line.startswith('ND '): 
     # ...