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

前端之家收集整理的这篇文章主要介绍了python – 删除巨大的csv中已知的确切行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_1@我有一个~2亿行,7列csv文件.我需要删除第2636759行.
这个文件是7.7GB,超过内存容量.我对R最熟悉,但也可以在 python或bash中做到这一点.

我无法在一次操作中读取或写入此文件.在磁盘上以增量方式构建此文件的最佳方法是什么,而不是尝试在内存中执行此操作?

我试图在SO上找到它,但只能找到如何使用足够小的文件来读取/写入内存,或者使用位于文件开头的行.

解决方法

一个python解决方案:
  1. import os
  2. with open('tmp.csv','w') as tmp:
  3.  
  4. with open('file.csv','r') as infile:
  5. for linenumber,line in enumerate(infile):
  6. if linenumber != 10234:
  7. tmp.write(line)
  8.  
  9. # copy back to original file. You can skip this if you don't
  10. # mind (or prefer) having both files lying around
  11. with open('tmp.csv','r') as tmp:
  12. with open('file.csv','w') as out:
  13. for line in tmp:
  14. out.write(line)
  15.  
  16. os.remove('tmp.csv') # remove the temporary file

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

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

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

  1. test = lambda line : 'NOVEMBER' in line
  2. with open('tmp.csv','w') as tmp:
  3. ...
  4. if test(line):
  5. ...

In-place read-writesmemory mapped file objects(可能相当快)将需要更多的簿记

猜你在找的Python相关文章