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

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

我一直在尝试将多个 python 模块添加到一个 zip 文件中。但是,我没有成功,因为新添加的模块正在替换以前的模块,我不明白其中的关系。 command_utils 添加一个 util 文件,然后 command_utils2 添加另一个模块,之后整个第一个模块都消失了。基本上我想在用源代码制作 zip 文件后将我的 2 个模块添加到 zip 文件中。这是我的代码。

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

使用 zipfile 模块:

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

注意我对 zip 文件使用 a 模式而不是 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.