问题从文本文件中删除多行重复

时间:2020-09-22 12:29:36

标签: python

我正在尝试从文本文件中删除重复的行并保持面对的问题...输出文件始终将前两个帐户放在同一行。每个帐户应有不同的行...有人知道为什么会发生这种情况以及如何解决该问题吗?

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

accounts_No_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'}

3 个答案:

答案 0 :(得分:2)

文件的最后一行缺少换行符(从技术上讲违反了POSIX standards for text files,但很常见,您必须要考虑到换行符),因此,"@account4\n"相对于{ {1}}结尾。我建议无条件地删除换行符,并在编写时将其重新添加:

"@account4"

在现代Python(CPython / PyPy 3.6+,任何解释器为3.7+)上,您可以使用with open('accounts.txt', 'r') as f: unique_lines = {line.rstrip("\r\n") for line in f} # Remove newlines for consistent deduplication with open('accounts_No_Dup.txt', 'w') as f: f.writelines(f'{line}\n' for line in unique_lines) # Add newlines back 而不是dict来保留首次出现的顺序。只需将文件读取内容更改为:

set

,您会在第一次出现时按顺序看到每一行,随后的重复项将被忽略。

答案 1 :(得分:1)

您的问题是set更改了行的顺序,并且最后一个元素不以\n结尾,因为文件末尾没有空行。

只需添加分隔符或不使用set

with open('accounts.txt', 'r') as f:
    unique_lines = set()
    for line in f.readlines():
        if not line.endswith('\n'):
            line += '\n'
        unique_lines.add(line)


with open('accounts_No_Dup.txt', 'w') as f:
    f.writelines(unique_lines)

答案 2 :(得分:0)

您可以轻松地使用unique关键字

代码如下

import pandas as pd

data = pd.read_csv('d:\\test.txt', sep="/n", header=None)
df =  pd.DataFrame(data[0].unique())

with open('d:\\testnew.txt', 'a') as f:
    f.write(df.to_string(header = False, index = False)))

结果:要读取的测试文件具有数据

enter image description here

结果是它删除了重复的行

enter image description here

相关问题