ZZzzZZzz
ZZzzZZzz

Reputation: 1844

How to add multiple folders into a zip file (add folder1, folder2 to myzip.zip filr containing few files)

I have been trying to add multiple python modules into a zip file. However, I am unsuccessful as the the newly added module is replacing the previous one and I don't understand the relation. command_utils adds a util file and the next command_utils2 adds another module after which the entire first module is gone. Basically I want to add 2 of my modules to a zip file after making the zip file out of source code. Here is my code.

import shutil
import os
import subprocess

zip_name = os.getcwd().split("/")[-1]

project_dir = '/tmp/'

shutil.make_archive(zip_name, "zip", project_dir+"test/")

os.chdir('/tmp/')
command_utils = 'zip -r '+project_dir+'test/'+zip_name+'platformutils'
print os.getcwd()
command_utils2 = 'zip -r '+project_dir+'test/'+zip_name+' pytz'
command_delete_archive = 'zip -d '+project_dir+'test/'+zip_name+'.zip '+zip_name+'.zip'
# command_update_function = 'aws lambda update-function-code --function-name 
'+zip_name+' --zip-file fileb://'+project_dir+zip_name+'/'+zip_name+'.zip'
# print command_utils
print command_utils2
print command_delete_archive
# print command_update_function
try:
   # c_u = subprocess.Popen(command_utils, shell=True, stdout=subprocess.PIPE)
   c_u2 = subprocess.Popen(command_utils2, shell=True, stdout=subprocess.PIPE)
   c_d_a = subprocess.Popen(command_delete_archive, shell=True, stdout=subprocess.PIPE)
   # p = subprocess.Popen(commands
except subprocess.CalledProcessError as e:
   raise e

Upvotes: 3

Views: 4623

Answers (1)

GIZ
GIZ

Reputation: 4633

Using zipfile module:

from zipfile import ZipFile
myzipfile = ZipFile("spam.zip", mode='a')
for mod_path in module_paths: 
    myzipfile.write(mod_path)
myzipfile.close()

Notice I used a mode for the zip file not w:

If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file (such as python.exe). If mode is 'a' and the file does not exist at all, it is created.

Upvotes: 4

Related Questions