首页 > 解决方案 > 将不同路径的新文件添加到 python 中的现有 zip 文件

问题描述

我有一个路径,路径中的所有文件都应该被压缩,一旦文件被压缩,我需要将不同文件路径中的不同文件添加到现有的 zip 文件夹中。我已经编写了代码来从第一个路径创建和压缩文件。有什么方法可以将不同路径中的文件附加到现有的 zip 文件夹中。

这是我的代码:

def _create_zip_folder(self, zip_path, base_path, pattern='.*'):
    zip = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)    
    rootlen = len(base_path)
    patterns = pattern.split(",")      
    regex = re.compile('|'.join(fnmatch.translate(p) for p in patterns))
    for base, _, files in os.walk(base_path):
        for file in files:                
           if regex.match(file):
              fn = os.path.join(base, file)        
              zip.write(fn, fn[rootlen:])

标签: pythonzipfile

解决方案


您可以在函数末尾添加:

some_other_path = '/some/other/path/a_file.ext'
name = some_other_path.split( os.path.sep )[-1]

zip.write( some_other_path, name )

推荐阅读