python对csv去除重复行_使用python脚本从csv文件中删除重复的行

这篇博客介绍如何用Python脚本删除CSV文件中的重复行。提供了两种解决方案:一种利用more_itertools库的unique_everseen函数,另一种通过创建集合来高效查找并跳过重复行。更新后的解决方案中还包含了一个就地修改原文件的方法。
摘要由CSDN通过智能技术生成

Goal

I have downloaded a CSV file from hotmail, but it has a lot of duplicates in it. These duplicates are complete copies and I don't know why my phone created them.

I want to get rid of the duplicates.

Approach

Write a python script to remove duplicates.

Technical specification

Windows XP SP 3

Python 2.7

CSV file with 400 contacts

解决方案

UPDATE: 2016

If you are happy to use the helpful more_itertools external library:

from more_itertools import unique_everseen

with open('1.csv','r') as f, open('2.csv','w') as out_file:

out_file.writelines(unique_everseen(f))

A more efficient version of @IcyFlame's solution

with open('1.csv','r') as in_file, open('2.csv','w') as out_file:

seen = set() # set for fast O(1) amortized lookup

for line in in_file:

if line in seen: continue # skip duplicate

seen.add(line)

out_file.write(line)

To edit the same file in-place you could use this

import fileinput

seen = set() # set for fast O(1) amortized lookup

for line in fileinput.FileInput('1.csv', inplace=1):

if line in seen: continue # skip duplicate

seen.add(line)

print line, # standard output is now redirected to the file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值