[英]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. 我一直试图将多个python模块添加到一个zip文件中。 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.
command_utils添加一个util文件,下一个command_utils2添加另一个模块,之后第一个模块消失了。 Basically I want to add 2 of my modules to a zip file after making the zip file out of source code.
基本上,在将zip文件从源代码中删除后,我想将2个模块添加到zip文件中。 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
Using zipfile module: 使用zipfile模块:
from zipfile import Zipfile
myzipfile = ZipFile("spam.zip", mode='a')
for mod_path in module_paths:
myzipfile.write(mod)
myzipfile.close()
Notice I used a
mode for the zip file not w
: 注意,我对zip文件使用
a
模式不是w
:
If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it.
如果mode为'a'并且文件引用现有的ZIP文件,则将其他文件添加到其中。 If file does not refer to a ZIP file, then a new ZIP archive is appended to the file.
如果文件不引用ZIP文件,则将新的ZIP存档附加到文件中。 This is meant for adding a ZIP archive to another file (such as python.exe).
这是为了将ZIP归档文件添加到另一个文件(例如python.exe)。 If mode is 'a' and the file does not exist at all, it is created.
如果mode为'a'并且文件根本不存在,则会创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.