Python 将多个文件夹从不同路径添加到单个zip文件夹

Python 将多个文件夹从不同路径添加到单个zip文件夹,python,Python,我有两个不同路径的文件夹,比如说path1/file1和path2/file2。我想将这两个文件压缩到一个压缩文件夹中。有什么方法可以做到这一点。请使用下面的命令 "zip -r total.zip pathoffolder1 pathoffolder2" 这很琐碎。比如说 import zipfile with zipfile.ZipFile("Your_zip_file_path.zip", "w") as myzip: myzip.write("path1") myzi

我有两个不同路径的文件夹,比如说path1/file1和path2/file2。我想将这两个文件压缩到一个压缩文件夹中。有什么方法可以做到这一点。

请使用下面的命令

"zip -r total.zip pathoffolder1 pathoffolder2"

这很琐碎。比如说

import zipfile

with zipfile.ZipFile("Your_zip_file_path.zip", "w") as myzip:
    myzip.write("path1")
    myzip.write("path2")

在写入
Zipfile
时,需要设置
arcname=“…”
,以在zip中创建新目录:

from pathlib import Path
import zipfile


def zipFlat(files, zipFolder, outFile):
    zipFolder = Path(zipFolder)
    zipf = zipfile.ZipFile(outFile, 'w')
    for file in files:
        filename = Path(file).name
        arcPath = zipFolder / Path(filename)
        zipf.write(file, arcname=str(arcPath))


filesToZip = ['/tmp/foo/bar/R.txt', '/tmp/foo/baz/Z.txt']
zipFlat(filesToZip, 'myArchiveDir', '/tmp/archive.zip')
生成的zip文件保存在“myArchiveDir”中:

# unzip -l archive.zip                                                                                                                        
Archive:  archive.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  01-15-2019 16:18   myArchiveDir/R.txt
        0  01-15-2019 16:18   myArchiveDir/Z.txt
---------                     -------
        0                     2 files