Python删除重复行

2024-06-16 10:02:52 发布

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

我编写了以下代码以从文件中获取所有IP地址并将其打印出来:

with open("C:\\users\\joey\\desktop\\access.log",'r') as bestand:
    for line in bestand:
        try:
            splittedline = line.split('sftp-session')[1].split("[")[1].split("]")[0]
        except Exception:
            continue
        print splittedline

以下代码打印另一个文件的所有IP地址:

^{pr2}$

如何比较这两个文件,只显示唯一的IP地址和删除重复?在

输出atm如下:

217.172.190.19
217.210.165.43
218.250.241.229
223.18.115.229
223.133.243.101

Tags: 文件代码logforaccessaswithline
1条回答
网友
1楼 · 发布于 2024-06-16 10:02:52

如果顺序不重要,请使用集合:

ips_1 = set()

with open("C:\\users\\joey\\desktop\\access.log",'r') as bestand:
    for line in bestand:
        try:
            ips1.add(linprint splittedlinee.split('sftp-session')[1].split("[")[1].split("]")[0])
        except Exception:
            continue

ips_2 = set()
with open("C:\\users\\joey\\desktop\\exit_nodes.csv",'r') as bestand:
    for line in bestand:
        ips_2.add(line)

然后,您可以使用set方法查看两个文件中的IP地址,这些IP地址只在一个文件中,或者获取所有唯一的IP地址:

两个文件中都有哪些IP?在

^{pr2}$

哪些IP只在文件1中?在

ips_1.difference(ips_2)

所有唯一IP:

ips_1.union(ips_2)

相关问题 更多 >