Sending multiple .CSV files to .ZIP without storing to disk in Python

前端 未结 3 2015
萌比男神i
萌比男神i 2020-12-31 17:50

I\'m working on a reporting application for my Django powered website. I want to run several reports and have each report generate a .csv file in memory that can be download

3条回答
  •  臣服心动
    2020-12-31 18:13

    def zipFiles(files):
        outfile = StringIO() # io.BytesIO() for python 3
        with zipfile.ZipFile(outfile, 'w') as zf:
            for n, f in enumarate(files):
                zf.writestr("{}.csv".format(n), f.getvalue())
        return outfile.getvalue()
    
    zipped_file = zip_files(myfiles)
    response = HttpResponse(zipped_file, content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename=my_file.zip'
    

    StringIO has getvalue method which return the entire contents. You can compress the zipfile by zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED). Default value of compression is ZIP_STORED which will create zip file without compressing.

提交回复
热议问题