我有一个~2亿行,7列csv文件.我需要删除行2636759.这个文件是7.7GB,超过内存容量.我对R最熟悉,但也可以在python或bash中做到这一点.
我无法在一次操作中读取或写入此文件.在磁盘上以增量方式构建此文件的最佳方法是什么,而不是尝试在内存中执行此操作?
我试图在SO上找到它,但只能找到如何使用足够小的文件来读取/写入内存,或者使用位于文件开头的行.
一个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
Run Code Online (Sandbox Code Playgroud)
这会复制数据,如果磁盘空间有问题,这可能不是最佳数据.如果不首先将整个文件加载到RAM中,则写入将更复杂
关键是python自然支持将文件作为iterables处理.这意味着它可以进行延迟评估,并且您永远不需要一次将整个内容保存在内存中
我喜欢这个解决方案,如果您的主要关注点不是原始速度,因为您可以linenumber != VALUE用任何条件测试替换该行,例如,过滤掉包含特定日期的行
test = lambda line : 'NOVEMBER' in line
with open('tmp.csv','w') as tmp:
...
if test(line):
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
554 次 |
| 最近记录: |