简体   繁体   English

用python将文本写入zipfile

[英]Write text into zipfile in python

I have a function which creates a zip archive with a textfile in it. 我有一个函数,可以创建一个带有文本文件的zip存档。 Is it possible to do this without creating a temporary file? 是否可以在不创建临时文件的情况下执行此操作?

import zipfile
import os

PROJ_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)))


def create_zip(name, text):
    with open(os.path.join(PROJ_DIR, "_tmp_file_"), "w+") as f: 
        f.write(text)

    zf = zipfile.ZipFile(os.path.join(PROJ_DIR, "%s.zip" % name), "w",
                         zipfile.ZIP_DEFLATED)
    zf.write(os.path.join(PROJ_DIR, "_tmp_file_"), "/file.txt")
    zf.close()

You can use writestr instead of write , an example 您可以使用writestr代替write ,这是一个示例

zf.writestr('/file.txt', text)

The documentation . 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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