2016-02-20 30 views
0

我有一個大文件。我想從中刪除一些行。我發現了一些其他類似的問題,但他們不是這樣的。該文件如下所示:在Python中查找和刪除行並輸出結果

A_B 3 
Line 1 
Line 2 
Line 3 

C_D 2 
Another Line 1 
Another line 2 

A_B 1 
Different line 1 

想象僅包含這些行的大文件。首先會有像A_B,C_D,E_G等不斷的字符串,然後會有可變的數字,如A_B 3,C_D 4等等。緊接着是那個行的數字,例如,如果有A_B 2,那麼它後面會跟着2線。如果有A_B 3,那麼它後面跟着3行。我想刪除「A_B(數字)」本身,並在其後面(行號)。在上面,輸出應該是:

C_D 2 
Another Line 1 
Another line 2 

我已經用Python編寫的腳本,它將打印我不想要什麼:

with open('file.txt') as oldfile: 
    for line in oldfile: 
     if 'A_B' in line: 
      number=line.split()[1] 

      num=int(number) 
      print 
      print line, 
      for i in range(num): 
       print next(oldfile), 
+0

那麼... *不*列印嗎? – skrrgwasme

+0

它應該打印除「A_B 2」行之外的所有其他行,以及之後的兩行。 – Err0rr

回答

2

我不知道,我明白你的問題,但我認爲,將做這項工作:

f = open("file.txt", "r") 
lines = f.readlines() 
f.close() 

f = open("file.txt", "w") 
num = 0 
for line in lines: 
    if num > 0: 
     num = num - 1 
    elif 'A_B' in line: 
     number = line.split()[1] 
     num = int(number) 
    else: 
     f.write(line) 
f.close() 
+1

感謝您的快速回答。有用。 – Err0rr

2

我不知道你爲什麼寫了一個程序來打印你不想要的一切。如果我的理解,這將打印你想要什麼:

with open('file.txt') as oldfile: 
    skip = 0 
    for line in oldfile: 
     if skip > 0: 
      skip -= 1 
     elif 'A_B' in line: 
      number = line.split()[1] 
      skip = int(number) 
     else: 
      print line 
+0

嘿,謝謝。感謝您的快速回答。我也會試試這個。 – Err0rr

1

這並您試圖測試中獲得的打印,不會刪除線。

MYFILE = '/path/to/longfile.txt' 

with open(MYFILE) as oldfile: 

    line = oldfile.readline() 
    while line: 
     if line.startswith('A_B'): 
      skip_counter = line.split()[1] 
      for _ in xrange(int(skip_counter)): 
       oldfile.readline() 
     else: 
      print line 

     line = oldfile.readline() 

輸出:

C_D 2 
Another Line 1 
Another line 2 
+0

嘿,謝謝。感謝您的快速回答。我也會試試這個。 – Err0rr

3
unwanted_headers=['A_B'] 
skip_this_many=0 

with open('file.txt','r') as oldfile: 
    for line in oldfile: 
     if not skip_this_many: 
      for unwanted_header in unwanted_headers: 
       if line.startswith(unwanted_header): 
        skip_this_many=int(line.split()[1]) 
       else: 
        print line 
     else: 
      skip_this_many -= 1 
+0

嘿,謝謝。感謝您的快速回答。我也會試試這個。 – Err0rr