2016-09-29 52 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 '): 
     # ...