0

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

Mick
  • 413
  • 4
  • 14

2 Answers2

1

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
Mick
  • 413
  • 4
  • 14
-1

You could simply write each of the string into it's own file inside a folder you mkdir and then zip it with the zipfile library or by using shutil which is part of python standard library. Once you have written the string into a directory of your choice you can do:

import shutil

shutil.make_archive('strings_archive.zip', 'zip', 'folder_to_zip')

reference.

Yacine Mahdid
  • 723
  • 5
  • 17