如何删除或跳过文本文件中的行列表,并在新的文本文件中打印其余行?

时间:2019-04-07 22:26:38

标签: python-3.x

我对python非常陌生。我正在尝试创建一个将文本行打印到排除行列表的文本文件的脚本。错误IndexError : List index out of range是由于.pop函数引起的吗?

with open(file_path) as f:

    lines = []
    lines = open(f,'r').readlines() 

    # delete the following lines from the textfile
    skip_line =[14,27,39,56,78]

    while skip_line:
        pop = skip_line.pop(0)
        print(pop)
        print(lines[pop])

        lines.remove(lines[pop])

        with open('duplicates_removed.txt', 'w') as savefile:
                savefile.writelines(lines)
        savefile.close()

我希望在lines[pop]中找到的行将从lines中删除。

实际结果:

IndexError : List index out of range

1 个答案:

答案 0 :(得分:0)

skip_lines = {14, 27, 39, 56, 78}

with open(filepath) as infile:
    with open("duplicates_removed.txt", "w") as outfile:
        for index, line in enumerate(infile):
            if index not in skip_lines:
                outfile.write(line)