Search code examples
pythondjangozip

Python convert list of strings to zip archive of files


In a python script, I have a list of strings where each string in the list will represent a text file. How would I convert this list of strings to a zip archive of files?

For example:

list = ['file one content \nblah \nblah', 'file two content \nblah \nblah']

I have tried variations of the following so far

import zipfile
from io import BytesIO
from datetime import datetime
from django.http import HttpResponse

def converting_strings_to_zip():

    list = ['file one content \nblah \nblah', 'file two content \nblah \nblah']

    mem_file = BytesIO()
    with zipfile.ZipFile(mem_file, "w") as zip_file:
        for i in range(2):
            current_time = datetime.now().strftime("%G-%m-%d")
            file_name = 'some_file' + str(current_time) + '(' + str(i) + ')' + '.txt'
            zip_file.writestr(file_name, str.encode(list[i]))

        zip_file.close()

    current_time = datetime.now().strftime("%G-%m-%d")
    response = HttpResponse(mem_file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="'str(current_time) + '.zip"'

    return response

But just leads to 0kb zip files


Solution

  • Was able to solve it by swapping a couple of lines (not resorting to saving the lists as files, then zipping files on the hard drive of the server, then loading the zip into memory and piping to the client like current answers suggest).

    import zipfile
    from io import BytesIO
    from datetime import datetime
    from django.http import HttpResponse
    
    def converting_strings_to_zip():
    
        list = ['file one content \nblah \nblah', 'file two content \nblah \nblah']
    
        mem_file = BytesIO()
        zip_file = zipfile.ZipFile(mem_file, 'w', zipfile.ZIP_DEFLATED)
        for i in range(2):
            current_time = datetime.now().strftime("%G-%m-%d")
            file_name = 'some_file' + str(current_time) + '(' + str(i) + ')' + '.txt'
            zip_file.writestr(file_name, str.encode(list[i]))
    
        zip_file.close()
    
        current_time = datetime.now().strftime("%G-%m-%d")
        response = HttpResponse(mem_file.getvalue(), content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename="'str(current_time) + '.zip"'
    
        return response