簡體   English   中英

如何將多個文件夾添加到zip文件中(將folder1,folder2添加到包含少量文件的myzip.zip filr中)

[英]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

如果mode為'a'並且文件引用現有的ZIP文件,則將其他文件添加到其中。 如果文件不引用ZIP文件,則將新的ZIP存檔附加到文件中。 這是為了將ZIP歸檔文件添加到另一個文件(例如python.exe)。 如果mode為'a'並且文件根本不存在,則會創建它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM