Python脚本删除文本文件中的重复行

文章介绍了如何用Python分别通过set和字典数据结构来删除文本文件a.txt中的重复行,同时提供了两种方法:Case1保持原始顺序,Case2不改变顺序但按出现顺序写入新文件b.txt。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例:需要用Python删除文本文件a.txt中的重复行.

Case1:仅需要删除文件中的重复行:

rFile = open('a.txt', 'r')
wFile = open('b.txt', 'w')
allLine = rFile.readlines()
rFile.close()
s = set()
for i in allLine:
    s.add(i)
for i in s:
    wFile.write(i)
open('b.txt', 'w').write(''.join(set(open('a.txt').readlines())))

Case2:删除文件中的重复行并保持原来的顺序:

rFile = open("a.txt", "r")
wFile = open("b.txt", "w")
allLine = rFile.readlines()
rFile.close()
h = {}
for i in allLine:
    if not h.has_key(i):
        h[i]=1
        wFile.write(i)
wFile.close()
lines, sorted = open('a.txt', 'r').readlines(), lambda a, cmp: a.sort(cmp=cmp) or a
open('b.txt', 'w').write(''.join([i[0] for i in sorted([(j, lines.index(j)) for j in set(lines)], lambda a,b: a[1]-b[1] )]))
h,r,w ={}, file('a.txt'), file('b.txt','w')
w.write(reduce(lambda x,y:x+y, [i for i in r if h.get(i)==None and h.setdefault(i, True)]))
s = []
[ s.append(k) for k in open('a.txt') if k not in s ]
open('b.txt', 'w').write(''.join(s))

上述两种方法均可以实现删除重复行的目的,感兴趣的可以再考虑其他方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值