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

前端 未结 3 2010
萌比男神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:30

    The stdlib comes with the module zipfile, and the main class, ZipFile, accepts a file or file-like object:

    from zipfile import ZipFile
    temp_file = StringIO.StringIO()
    zipped = ZipFile(temp_file, 'w')
    
    # create temp csv_files = [(name1, data1), (name2, data2), ... ]
    
    for name, data in csv_files:
        data.seek(0)
        zipped.writestr(name, data.read())
    
    zipped.close()
    
    temp_file.seek(0)
    
    # etc. etc.
    

    I'm not a user of StringIO so I may have the seek and read out of place, but hopefully you get the idea.

提交回复
热议问题