首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用python zipfile为zip文件添加注释?

如何使用python zipfile为zip文件添加注释?
EN

Stack Overflow用户
提问于 2014-05-22 15:11:17
回答 1查看 1.7K关注 0票数 0
代码语言:javascript
运行
复制
    $ echo "short"|zip -z test.zip
    enter new zip file comment (end with .):
    $ md5sum test.zip
    48da9079a2c19f9755203e148731dae9  test.zip
    $ echo "longlong"|zip -z test.zip
    current zip file comment is:
    short
    enter new zip file comment (end with .):
    $ md5sum test.zip
    3618846524ae0ce51fbc53e4b32aa35b  test.zip
    $ echo "short"|zip -z test.zip
    current zip file comment is:
    longlong
    enter new zip file comment (end with .):
    root@Debian:~# md5sum test.zip
    48da9079a2c19f9755203e148731dae9  test.zip
    $ echo "longlong"|zip -z test.zip
    current zip file comment is:
    short
    enter new zip file comment (end with .):
    $ md5sum test.zip
    3618846524ae0ce51fbc53e4b32aa35b  test.zip
    $
    $
    $ cat test.py
    #/usr/bin/env python
    #coding: utf-8

    import zipfile
    import subprocess

    zip_name = 'test.zip'

    def add_comment(zip_name, comment):
        with zipfile.ZipFile(zip_name, 'a') as zf:
            zf.comment = comment

    add_comment(zip_name, "short")
    print subprocess.Popen(['md5sum', zip_name], stdout=subprocess.PIPE).communicate()[0],
    add_comment(zip_name, "longlong")
    print subprocess.Popen(['md5sum', zip_name], stdout=subprocess.PIPE).communicate()[0],
    add_comment(zip_name, "short")
    print subprocess.Popen(['md5sum', zip_name], stdout=subprocess.PIPE).communicate()[0],
    add_comment(zip_name, "longlong")
    print subprocess.Popen(['md5sum', zip_name], stdout=subprocess.PIPE).communicate()[0],
    $
    $ python test.py 
    48da9079a2c19f9755203e148731dae9  test.zip
    3618846524ae0ce51fbc53e4b32aa35b  test.zip
    89c2038501f737991ca21aa097ea9956  test.zip
    3618846524ae0ce51fbc53e4b32aa35b  test.zip

在shell env中,第一次和第三次的"test.zip“md5值是相同的,第二次和第四次的"test.zip”zipfile值是相同的,但是当我使用python zipfile时,结果就不一样了。如何使用Python zipfile模块做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2014-05-22 15:31:38

zipfile.ZipFile() class有一个您可以设置的comment attribute

在append模式下打开文件,修改注释,关闭时会写出:

代码语言:javascript
运行
复制
from zipfile import ZipFile

with ZipFile('test.zip', 'a') as testzip:
    testzip.comment = 'short'

当您使用ZipFile作为上下文管理器时,就像常规文件一样,当退出with块时,它将自动关闭。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23800076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档