Python: Create in Memory Zip File

(Last Updated On: )

Sometimes we need to create a zip file in memory and save to disk or send to AWS or wherever we need to save it. Below is basic steps to do this.

  1. from zipfile import ZipFile
  2. from io import BytesIO
  3.  
  4. in_memory = BytesIO()
  5. zf = ZipFile(in_memory, mode="w")
  6.  
  7. #If you have data in text format that you want to save into the zip as a file
  8. zf.writestr("name", file_data)
  9.  
  10. #Close the zip file
  11. zf.close()
  12.  
  13. #Go to beginning
  14. in_memory.seek(0)
  15.  
  16. #read the data
  17. data = in_memory.read()
  18.  
  19. #You can save it to disk
  20. with open('file_name.zip','wb') as out:
  21.       out.write(data)