caveman
caveman

Reputation: 444

How to create a zip archive in Python without creating files on file system?

One easy way is to create a directory and populate it with files. Then archive and compress that directory into a zip file called, say, file.zip. But this approach is needless since my files are in memory already, and needing to save them to disk is excessive.

Is it possible that I create the directory structure right in memory, without saving the unzipped files/directories? So that I end up saving only the final file.zip (without the intermediate stage of saving files/directories on file system)?

Upvotes: 2

Views: 3145

Answers (1)

Martim
Martim

Reputation: 1086

You can use zipfile:

from zipfile import ZipFile

with ZipFile("file.zip", "w") as zip_file:
    zip_file.writestr("root/file.json", json.dumps(data))
    zip_file.writestr("README.txt", "hello world")

Upvotes: 2

Related Questions