[英]how to use python zipfile to append comment for a zip file?
$ 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
At shell env, the fist time and the third time, "test.zip" md5 values are the same, the second time and the forth time, "test.zip" md5 values are the same, but when i use python zipfile, the result is not like that. 在shell env,第一次和第三次,“test.zip”md5值是相同的,第二次和第四次,“test.zip”md5值是相同的,但是当我使用python zipfile时,结果不是那样的。 How can I do this with the Python
zipfile
module? 如何使用Python
zipfile
模块执行此操作?
The zipfile.ZipFile()
class has a comment
attribute you can set. zipfile.ZipFile()
类有一个可以设置的comment
属性 。
Open the file in append mode, alter the comment, and it'll be written out when closed: 以附加模式打开文件,更改注释,并在关闭时写出:
from zipfile import ZipFile
with ZipFile('test.zip', 'a') as testzip:
testzip.comment = 'short'
When you use a ZipFile
as a context manager, like a regular file it'll automatically be closed when the with
block is exited. 当您使用
ZipFile
作为上下文管理器时,就像常规文件一样,当退出with
块时它将自动关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.