Zip 多个文件夹 - Python

发布于 2025-01-13 13:35:53 字数 707 浏览 3 评论 0原文

我正在用 python 压缩多个文件夹 当我运行代码时,它创建 name1.zip 和 name2.zip 并打开 name1.zip 文件,它只显示 file1.pdf。

我正在尝试的是,当我打开 name1.zip 文件时,它将附带父文件夹 name1

文件夹结构

测试 -->名称1 --> file1.pdf

有人可以帮我吗 谢谢 这是我的代码:

import os

import zipfile

path = "/Users/Documents/test"

path = os.path.abspath(os.path.normpath(os.path.expanduser(path)))

for folder in os.listdir(path):
    zipf = zipfile.ZipFile('{0}.zip'.format(os.path.join(path, folder)), 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(os.path.join(path, folder)):
        for filename in files:
            zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)
    zipf.close()



I am working on zip the multiple folder in python
When i ran the code it's creating name1.zip and name2.zip and open the name1.zip file it only showing the file1.pdf.

What i am trying is when i open name1.zip file it will come with parent folder name1

Folder structure

test --> name1 --> file1.pdf

Could someone help me out
Thanks
This is my code:

import os

import zipfile

path = "/Users/Documents/test"

path = os.path.abspath(os.path.normpath(os.path.expanduser(path)))

for folder in os.listdir(path):
    zipf = zipfile.ZipFile('{0}.zip'.format(os.path.join(path, folder)), 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(os.path.join(path, folder)):
        for filename in files:
            zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)
    zipf.close()



如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆沫 2025-01-20 13:35:53

这就是 arcname 参数的用途。尝试

zipf.write(
    os.path.abspath(os.path.join(root, filename)),
    arcname=os.path.relpath(os.path.join(root, filename), start=path)
)

而不是

zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)

另外,看看 pathlib。恕我直言,使代码更具可读性。

That's what the arcname parameter is for. Try

zipf.write(
    os.path.abspath(os.path.join(root, filename)),
    arcname=os.path.relpath(os.path.join(root, filename), start=path)
)

instead of

zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)

Also, have a look at pathlib. Makes for more readable code IMHO.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文