使用python拆分大文件

新手上路,请多包涵

我在尝试拆分大文件(比如大约 10GB)时遇到了一些麻烦。基本思想是简单地读取行,并将每行分组,比如 40000 行到一个文件中。但是有两种“读取”文件的方法。

1)第一个是一次读取整个文件,并将其制成一个列表。但这将需要将整个文件加载到内存中,这对于太大的文件来说是痛苦的。 (我想我以前问过这样的问题)在 python 中,我尝试过一次读取整个文件的方法包括:

 input1=f.readlines()

input1 = commands.getoutput('zcat ' + file).splitlines(True)

input1 = subprocess.Popen(["cat",file],
                              stdout=subprocess.PIPE,bufsize=1)

好吧,那么我可以通过以下方式轻松地将 40000 行分组到一个文件中: list[40000,80000] or list[80000,120000] 或者使用列表的优点是我们可以轻松地指向特定的行。

2)第二种方式是逐行读取;读取时处理该行。那些读取的行不会保存在内存中。例子包括:

 f=gzip.open(file)
for line in f: blablabla...

或者

for line in fileinput.FileInput(fileName):

我确定对于 gzip.open,这个 f 不是一个列表,而是一个文件对象。似乎我们只能逐行处理;那么我该如何执行这个“拆分”工作呢?如何指向文件对象的特定行?

谢谢

原文由 LookIntoEast 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 419
2 个回答
NUM_OF_LINES=40000
filename = 'myinput.txt'
with open(filename) as fin:
    fout = open("output0.txt","wb")
    for i,line in enumerate(fin):
      fout.write(line)
      if (i+1)%NUM_OF_LINES == 0:
        fout.close()
        fout = open("output%d.txt"%(i/NUM_OF_LINES+1),"wb")

    fout.close()

原文由 yurib 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果每个文件中有特定数量的文件行没有什么特别之处,那么 readlines() 函数 也接受一个大小“提示”参数,其行为如下:

如果给定一个可选参数 sizehint,它会从文件中读取足够多的字节来完成一行,然后从中读取这些行。这通常用于允许按行高效地读取大文件,但不必将整个文件加载到内存中。只会返回完整的行。

…所以你可以这样写代码:

 # assume that an average line is about 80 chars long, and that we want about
# 40K in each file.

SIZE_HINT = 80 * 40000

fileNumber = 0
with open("inputFile.txt", "rt") as f:
   while True:
      buf = f.readlines(SIZE_HINT)
      if not buf:
         # we've read the entire file in, so we're done.
         break
      outFile = open("outFile%d.txt" % fileNumber, "wt")
      outFile.write(buf)
      outFile.close()
      fileNumber += 1

原文由 bgporter 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题