2014-12-05 89 views
0

我有一個文件,我需要刪除文件中間的一些行。Python:刪除文件中的多行

我需要刪除的行在開頭和結尾都有一個關鍵字。

例子:

aaaaaaaaaaaaaaaaa 
bbbbbbbbbbbbbbbbb 
ccccccccccccccccc 
ddddddddddddddddd 
Begintoremove 
eeeeeeeeeeeeeeeee 
fffffffffffffffff 
ggggggggggggggggg 
hhhhhhhhhhhhhhhhh 
EndofRemove 
iiiiiiiiiiiiiiiii 
jjjjjjjjjjjjjjjjj 
kkkkkkkkkkkkkkkkk 
lllllllllllllllll 

我需要有一個腳本,肯定是蟒蛇,以關鍵字「Begintoremove」和「EndofRemove」之間刪除文本的一部分。

您認爲如果可以,可以使用哪個Python函數?

+1

我想是的,但你應該嘗試一下當然,這是可以做到的第一 – 2014-12-05 13:34:11

+1

,你試一試;-) 。用linewise讀取文件,對於讀取的每一行,使用函數'line.startswith(「Begintoremove」)'開始刪除,直到'line.startswith(「EndRemove」)'爲True – Tengis 2014-12-05 13:35:50

回答

0
f = open('filename') 
lines = f.readlines() 
f.close() 

result = [] 
bool_remover = False 
for line in lines: 
    if line == "Begintoremove" : bool_remover = True 
    if not bool_remover : result.append(line) 
    if line == "EndofRemove" : bool_remover = False 

我在結果中不包括「Begintoremove」和「EndofRemove」。從文件

1
with open('file_path', 'r') as my_file: 
    file_lines = my_file.readlines() 

first_part = file_lines[:file_lines.index('Begintoremove')] 
second_part = file_lines[file_lines.index('Endtoremove') + 1:] 

lines = first_part + second_part 
with open('file_path', 'w') as my_file: 
    my_file.writelines(lines) 
0

讀取行,並將它們複製到第二個根據當前copying狀態:

copying = True 
with open('input_file.txt', 'rt') as inf, open('output_file.txt', 'wt') as outf: 
    for line in inf: 
     if copying: 
      if line.startswith('Begintoremove'): 
       copying = False 
      else: 
       outf.write(line) 
     elif line.startswith('EndofRemove'): 
      copying = True