Python将字符串列表转换为文件的zip存档

2024-09-28 05:27:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在python脚本中,我有一个字符串列表,其中列表中的每个字符串将表示一个文本文件。如何将此字符串列表转换为文件的zip存档

例如:

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

到目前为止,我已经尝试了以下几种变体

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

但只会导致0kb的zip文件


Tags: 字符串fromimport列表datetimetimeresponsecontent
2条回答

可以通过交换几行代码来解决这个问题(而不是像当前答案所建议的那样将列表保存为文件,然后在服务器的硬盘上压缩文件,然后将压缩文件加载到内存并通过管道传输到客户端)

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

您可以简单地将每个字符串写入mkdir文件夹中它自己的文件,然后使用zipfile库或使用作为python标准库一部分的shutil压缩它。 将字符串写入所选目录后,可以执行以下操作:

import shutil

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

reference

相关问题 更多 >

    热门问题