python从文本文件中删除下一行和上一行。基于样本

时间:2014-01-20 15:23:43

标签: python python-2.7

我必须从textfile以及上一行和下一行中删除指定的行。 我可以删除指定的行,但我不知道如何删除下一行和前一行。 这是我的代码

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') 

此脚本不会将包含示例的行移动到新文件中 我怎样才能避免上一行和下一行?

3 个答案:

答案 0 :(得分: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变量。

答案 1 :(得分: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']

答案 2 :(得分: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