@H_502_1@我有一个~2亿行,7列csv文件.我需要删除第2636759行.
这个文件是7.7GB,超过内存容量.我对R最熟悉,但也可以在 python或bash中做到这一点.
这个文件是7.7GB,超过内存容量.我对R最熟悉,但也可以在 python或bash中做到这一点.
解决方法
一个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):
- ...
In-place read-writes和memory mapped file objects(可能相当快)将需要更多的簿记