Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 830
Anton Avatar asked Jun 17 '26 13:06

Anton


1 Answers

You can use writestr instead of write, an example

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

The documentation.

like image 135
Christian Witts Avatar answered Jun 19 '26 03:06

Christian Witts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!