python删除csv某一行_python – 删除巨大的csv中已知的确切行

一个python解决方案:

import os

with open('tmp.csv','w') as tmp:

with open('file.csv','r') as infile:

for linenumber,line in enumerate(infile):

if linenumber != 10234:

tmp.write(line)

# copy back to original file. You can skip this if you don't

# mind (or prefer) having both files lying around

with open('tmp.csv','r') as tmp:

with open('file.csv','w') as out:

for line in tmp:

out.write(line)

os.remove('tmp.csv') # remove the temporary file

这会复制数据,如果磁盘空间有问题,这可能不是最佳数据.如果不首先将整个文件加载到RAM中,则写入将更复杂

关键是python自然支持处理files as iterables.这意味着它可以被懒惰地评估,你永远不需要一次把整个东西保存在内存中

我喜欢这个解决方案,如果您的主要关注点不是原始速度,因为您可以用任何条件测试替换行亚麻布!= VALUE,例如,过滤掉包含特定日期的行

test = lambda line : 'NOVEMBER' in line

with open('tmp.csv','w') as tmp:

...

if test(line):

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值