6

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()
Dharman
  • 30,962
  • 25
  • 85
  • 135
Anton
  • 2,217
  • 3
  • 21
  • 34

1 Answers1

10

You can use writestr instead of write, an example

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

The documentation.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46