How to compress csv file into zip archive directly?

后端 未结 2 1103
梦毁少年i
梦毁少年i 2021-01-11 09:49

I am generating a number of csv files dynamically, using the following code:

import csv
fieldnames = [\'foo1\', \'foo2\', \'foo3\', \'foo4\']
with open(csvfi         


        
相关标签:
2条回答
  • 2021-01-11 10:22

    Thanks kroolik It's done with little modification.

    with ZipFile(your_zip_file, 'w', ZIP_DEFLATED) as zip_file:
        string_buffer = StringIO()
        csvwriter = csv.DictWriter(string_buffer, delimiter=',', fieldnames=fieldnames)
        csvwrite.writeheader()
        for row in cdrdata:
            csvwrite.writerow(row)
        zip_file.writestr(filename + '.csv', string_buffer.getvalue())
    
    0 讨论(0)
  • 2021-01-11 10:24

    Use the cStringIO.StringIO object to imitate a file:

    with ZipFile(your_zip_file, 'w', ZIP_DEFLATED) as zip_file:
        string_buffer = StringIO()
        writer = csv.writer(string_buffer)
    
        # Write data using the writer object.
    
        zip_file.writestr(filename + '.csv', string_buffer.getvalue())
    
    0 讨论(0)
提交回复
热议问题