如何使用Python zipfile为zip文件添加注释?
$ 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
在命令行环境中,第一次和第三次对“test.zip”文件计算的md5值是一样的;而第二次和第四次的md5值也是一样的。但是当我用Python的zipfile模块来处理时,结果却不一样。请问我该如何使用Python的zipfile
模块来做到这一点呢?
1 个回答
2
zipfile.ZipFile()
类有一个可以设置的comment
属性。
你可以以追加模式打开文件,修改评论内容,然后在关闭文件时,这些修改会被保存:
from zipfile import ZipFile
with ZipFile('test.zip', 'a') as testzip:
testzip.comment = 'short'
当你把 ZipFile
当作上下文管理器使用时,就像普通文件一样,当你退出 with
代码块时,它会自动关闭。