删除匹配模式之前的空行

时间:2018-07-02 13:26:24

标签: python

我试图在匹配'find me'之前写新行,但是我的代码向输出文件写了空行。如何摆脱空行(41.4克后的行)?

    with open("input.txt", "r") as infile:
        readcontent = infile.readlines()

    with open("output.txt", "w") as out_file:
        for line in readcontent:
            if line.strip() == 'find me':
                out_file.write('Added New line')
            out_file.write(line)

input.txt:

[atom]
molecules 
41.4 gram

find me
2.1 kcal
completed

获得output.txt:

[atom]
molecules 
41.4 gram

Added New line
find me
2.1 kcal
completed

所需的output.txt:

[atom]
molecules 
41.4 gram
Added New line
find me
2.1 kcal
completed

2 个答案:

答案 0 :(得分:1)

在您追逐空白行时。我们以.isspace作为检查对象,并且您永远不会写任何空白行或仅包含空白字符的行。

with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for line in readcontent:
        if line.strip() == 'find me':
            out_file.write('Added New line')
        if not line.isspace:
            out_file.write(line)

编辑:根据下面的评论者进行了更改

答案 1 :(得分:1)

换句话说,如果下一行是find me,则要跳过输出空白行。由于您已经拥有readcontent中的所有行,因此可以简单地浏览下一个索引:

with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for index, line in enumerate(readcontent):
        if not line.strip() and readcontent[index + 1].strip() == 'find me':
            continue
        if line.strip() == 'find me':
            out_file.write('Added New line\n')
        out_file.write(line)