2

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)?

4
  • 1
    Possible duplicate of stackoverflow.com/questions/2463770/… Commented Aug 25, 2020 at 21:21
  • @S4rt-H4K I don't think it says how to add a directory structure to it. E.g. add a folder/directory to it. Thoughts? Commented Aug 26, 2020 at 9:45
  • do you want to add files in multiple directories? Commented Aug 26, 2020 at 11:09
  • Just 1 directory. Or maybe multiple. Not quite sure about their number yet. Commented Aug 26, 2020 at 11:44

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me, but there is a typo: in the import Zipfile should be ZipFile (with a capital F)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.