我正在尝试从文本文件中删除重复的行,并一直面临问题。。。输出文件一直将前两个帐户放在同一行上。每个帐户应有不同的行。。。有人知道为什么会发生这种情况以及如何解决吗
with open('accounts.txt', 'r') as f:
unique_lines = set(f.readlines())
with open('accounts_No_Dup.txt', 'w') as f:
f.writelines(unique_lines)
accounts.txt:
@account1
@account2
@account3
@account4
@account5
@account6
@account7
@account5
@account8
@account4
帐户\u No\u Dup.txt:
@account4@account3
@account4
@account8
@account5
@account7
@account1
@account2
@account6
打印(唯一行)
{'@account4', '@account7\n', '@account3\n', '@account6\n', '@account5\n', '@account8\n', '@account4\n', '@account2\n', '@account1\n'}
您的问题是
set
会更改行的顺序,并且最后一个元素不会以\n
结尾,因为文件末尾没有空行只需添加分隔符,或者不使用
set
您可以使用
unique
关键字轻松地完成它代码如下
结果:要读取的测试文件包含数据
结果是它删除了重复的行
文件中的最后一行缺少换行符(从技术上讲,这是对POSIX standards for text files的违反,但您必须对此加以说明),因此前面的
"@account4\n"
被解释为相对于末尾的"@account4"
是唯一的。我建议无条件地剥离换行符,并在编写时重新添加它们:顺便说一句,在现代Python上(对于任何解释器,CPython/pypy3.6+,3.7+),您可以通过使用
dict
而不是set
来保持第一次出现的顺序。只需将文件的读取更改为:您将在第一次看到每一行时看到它,以该顺序显示,随后的重复项将被忽略
相关问题 更多 >
编程相关推荐