如何压缩文件夹的内容而不是文件夹

How to zip contents of but not the folder

我正在使用以下文件夹结构:

.
+-- temp
|   +-- sample1.csv
|   +-- sample2.csv
+-- zips
|   +-- zip1.zip
|   +-- zip2.zip
+-- main.py

我想将 temp 文件夹的内容压缩到一个 zip 文件中,但我不想包含该文件夹。我尝试了以下方法(希望只压缩文件):

import pathlib
import zipfile

origin = pathlib.Path('.') / 'temp'
destination = pathlib.Path('.') / 'zips' / 'zip3.zip'

with zipfile.ZipFile(destination, mode='w') as zipfile_:
    for content in origin.iterdir():
        zipfile_.write(content)

我也尝试过使用 shutil.make_archive(),但结果相同,唯一的区别是目录被简单地命名为 "."


编辑:谢谢 CookieReaver and metatoaster (I believe) for pointing out that ZipFile.write() method has an argument called arcname that will name the file (ZipFile.write() documentation)。

这是我应用修复后的原始问题:

import pathlib
import zipfile

origin = pathlib.Path('.') / 'temp'
destination = pathlib.Path('.') / 'zips' / 'zip3.zip'

with zipfile.ZipFile(destination, mode='w') as zipfile_:
    for content in origin.iterdir():
        zipfile_.write(content, content.name)
import zipfile
import os

orig = r"path_to_origin_dir"
dest = r"path_to_destination_dir"

zip_name = "zip3.zip"
target_zip = zipfile.ZipFile(os.path.join(dest, zip_name), 'w')

for dp, dn, fn in os.walk(orig):

    for filename in fn:
        if filename.endswith('csv'):
            target_zip.write(os.path.join(dp, filename), os.path.relpath(os.path.join(dp, filename), orig))

target_zip.close()

这是你的目标吗?