如何从文件中删除重复行?

2024-04-25 07:57:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个只有一列的文件。如何删除文件中的重复行


Tags: 文件
3条回答
uniqlines = set(open('/tmp/foo').readlines())

这将为您提供唯一行的列表

将其写回某个文件将非常简单:

bar = open('/tmp/bar', 'w').writelines(set(uniqlines))

bar.close()

在Unix/Linux上,按照David Locke的回答使用uniq命令,或者按照William Pursell的评论使用sort

如果需要Python脚本:

lines_seen = set() # holds lines already seen
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
    if line not in lines_seen: # not a duplicate
        outfile.write(line)
        lines_seen.add(line)
outfile.close()

更新:组合sort/uniq将删除重复项,但返回一个已排序行的文件,这可能是您想要的,也可能不是您想要的。上面的Python脚本不会对行重新排序,只会删除重复的行。当然,要让上面的脚本也进行排序,只需省略outfile.write(line),而是在循环之后立即执行outfile.writelines(sorted(lines_seen))

如果打开*nix,请尝试运行以下命令:

sort <file name> | uniq

相关问题 更多 >