Create a zip file from a generator in Python?

后端 未结 10 1902
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 07:32

I\'ve got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can\'t load it all into memory at once to pass to the .writestr method of ZipFil

10条回答
  •  旧时难觅i
    2020-11-30 08:11

    gzip.GzipFile writes the data in gzipped chunks , which you can set the size of your chunks according to the numbers of lines read from the files.

    an example:

    file = gzip.GzipFile('blah.gz', 'wb')
    sourcefile = open('source', 'rb')
    chunks = []
    for line in sourcefile:
      chunks.append(line)
      if len(chunks) >= X: 
          file.write("".join(chunks))
          file.flush()
          chunks = []
    

提交回复
热议问题