简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM