2014-01-20 71 views
0

我必須從文本文件以及上一行和下一行刪除指定的行。 我可以刪除指定的行,但我不知道如何刪除下一個和上一個。 這裏是我的代碼python從文本文件中刪除下一行和前一行。基於樣本

def Parser(line): 
global destination 
if "CHECKIN" in line: 
    splitted = line.split() 
    destination = open(ea_xml_dest,'r') 
    lines = destination.readlines() 
    destination = open(ea_xml_dest,'w') 
    sample = str(splitted[5][:-1]) 
    for i in lines: 
     if sample not in i: 
      destination.write(i) 
    destination.close() 
    destination = open(ea_xml_dest,'r') 

這個腳本不動什麼包含樣品到新文件 如何避免以前和下一行的行?

回答

1

您必須在搜索到的substr 中找到該行的索引並將其保存到變量(found)。 比你從原始lines全部到''之前的行':' 和所有在''之後的行'之後。

found = None 
for i,s in enumerate(lines): 
    if substr in s: 
    found = i 
    break 

if found: 
    lines = lines[:found-1] + lines[found+2:] 

如果發現沒有,你只是離開了lines變量,因爲它是。

+0

下一個元素髮現後,將不被刪除 lines = lines [:found-1] + lines [found + 2 :] – phoenix

+0

@phoenix:謝謝你,鳳凰! –

0

如果這是你可以改變的代碼的唯一部分,那麼你將不得不做一些非常混亂的事情。

如果您有更多的靈活性,那麼你可以做這樣的事情:

with open("lines.dat","r") as f: 

    previousLine = "" 
    lines = [] 
    checkinCounter = 1 

    for line in f: 

    if checkinCounter > 0: 
     checkinCounter -= 1 

    elif "CHECKIN" in line: 
     checkinCounter = 2 

    else: 
     lines.append(previousLine.strip()) 

    previousLine = line 

print lines 

其中lines.dat

1 
2 
3 
4 
5 
CHECKIN 
6 
7 
8 
9 
CHECKIN 
10 
11 
12 
23 
24 
156146 

輸出['1', '2', '3', '4', '7', '8', '11', '12', '23', '24', '156146']

0
with open('in.txt') as in_file: 
    it = iter(in_file) 
    prev = None 
    line = it.next() 
    while line: 
     next = iter.next() 
     # condition goes here 
     # if line found .... 
     prev = line 
     line = next 
相關問題