【发布时间】:2019-05-27 04:42:45
【问题描述】:
我正在尝试创建一个从文件中删除重复行的简单程序。但是,我被困住了。我的目标是最终删除除 1 个重复行之外的所有重复行,与建议的重复行不同。所以,我还有那个数据。我也想这样做,它接受相同的文件名并输出相同的文件名。当我尝试使文件名相同时,它只会输出一个空文件。
input_file = "input.txt"
output_file = "input.txt"
seen_lines = set()
outfile = open(output_file, "w")
for line in open(input_file, "r"):
if line not in seen_lines:
outfile.write(line)
seen_lines.add(line)
outfile.close()
输入.txt
I really love christmas
Keep the change ya filthy animal
Pizza is my fav food
Keep the change ya filthy animal
Did someone say peanut butter?
Did someone say peanut butter?
Keep the change ya filthy animal
预期输出
I really love christmas
Keep the change ya filthy animal
Pizza is my fav food
Did someone say peanut butter?
【问题讨论】:
-
您打开文件两次,因为
input_file和output_file是相同的。第二次打开为已读,我认为这是您的问题所在。所以你将无法写作。 -
@busybear 是的。以
r+身份打开您的文件以同时读取和写入文件(它们都可以工作)。
标签: python text-files