Anton
Anton

Reputation: 2378

Write text into zipfile in python

I have a function which creates a zip archive with a textfile in it. 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()

Upvotes: 8

Views: 9054

Answers (1)

Christian Witts
Christian Witts

Reputation: 11585

You can use writestr instead of write, an example

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

The documentation.

Upvotes: 13

Related Questions