该PKZIP文件是高度结构化的,只是追加到最后会把它搞砸了。我不能说早期版本的工作,但解决这个问题的方法是打开一个zip文件进行阅读,打开一个新的文件,提取第一个文件的内容,然后在最后添加你的添加组件。完成后,用新创建的文件替换原始的zip文件。
运行代码时运行代码时我得到的回溯是:
Traceback (most recent call last):
File "zip.py", line 19, in <module>
Foo()
File "zip.py", line 17, in Foo
print zip.read("bar")
File "/usr/lib/python2.6/zipfile.py", line 834, in read
return self.open(name, "r", pwd).read()
File "/usr/lib/python2.6/zipfile.py", line 874, in open
zinfo.orig_filename, fname)
zipfile.BadZipfile: File name in directory "bar" and header "foo" differ.
经仔细检查,我注意到,你从一个类文件StringIO的阅读与“a'ppend模式打开它应该导致读取错误,因为'a'通常不可读,并且当然必须在读取和写入之间寻找()。我会欺骗一些并更新它。
更新:
偷了几乎所有从道格·赫尔曼的优秀Python Module of the Week这个代码,我发现它的作品如我所料相当多。人们不能仅仅附加到一个结构化的PKZIP文件,如果在原来的职位代码做过的工作,这是意外:
import zipfile
import datetime
def create(archive_name):
print 'creating archive'
zf = zipfile.ZipFile(archive_name, mode='w')
try:
zf.write('/etc/services', arcname='services')
finally:
zf.close()
def print_info(archive_name):
zf = zipfile.ZipFile(archive_name)
for info in zf.infolist():
print info.filename
print '\tComment:\t', info.comment
print '\tModified:\t', datetime.datetime(*info.date_time)
print '\tSystem:\t\t', info.create_system, '(0 = Windows, 3 = Unix)'
print '\tZIP version:\t', info.create_version
print '\tCompressed:\t', info.compress_size, 'bytes'
print '\tUncompressed:\t', info.file_size, 'bytes'
print
zf.close()
def append(archive_name):
print 'appending archive'
zf = zipfile.ZipFile(archive_name, mode='a')
try:
zf.write('/etc/hosts', arcname='hosts')
finally:
zf.close()
def expand_hosts(archive_name):
print 'expanding hosts'
zf = zipfile.ZipFile(archive_name, mode='r')
try:
host_contents = zf.read('hosts')
finally:
zf.close
zf = zipfile.ZipFile(archive_name, mode='a')
try:
zf.writestr('hosts', host_contents + '\n# hi mom!')
finally:
zf.close()
def main():
archive = 'zipfile.zip'
create(archive)
print_info(archive)
append(archive)
print_info(archive)
expand_hosts(archive)
print_info(archive)
if __name__ == '__main__': main()
值得注意的是,从上一次调用输出到print_info
:
...
hosts
Modified: 2010-05-20 03:40:24
Compressed: 404 bytes
Uncompressed: 404 bytes
hosts
Modified: 2010-05-27 11:46:28
Compressed: 414 bytes
Uncompressed: 414 bytes
它没有附加到现有的arcname'hosts',它创建了一个额外的存档成员。
“济n'ai既成事实勒慈加椅阙 parce阙乙脑n'ai PAS欧盟乐德罗伊萨拉 放任加courte。”
- 帕斯卡