我对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
答案 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)