Python:删除文件中的多行

时间:2014-12-05 13:32:44

标签: python python-2.7

我有一个文件,我需要删除文件中间的一些行。

我需要删除的行在开头和结尾都有一个关键字。

示例:

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

我需要有一个脚本,当然是在python中,删除关键字" Begintoremove"之间的文本部分。和#34; EndofRemove"。

您认为可以做到这一点,如果可以的话,使用哪种Python函数?

3 个答案:

答案 0 :(得分:1)

从文件中读取行并将其复制到第二行,具体取决于当前的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

答案 1 :(得分: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”。

答案 2 :(得分:0)

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)