我目前正在爲容器格式編寫一個開放源代碼庫,其中涉及修改zip檔案。所以我利用pythons內置的zipfile模塊。由於一些限制,我決定修改模塊並將其與我的庫一起發貨。這些修改包括一個修補程序,用於從python問題跟蹤器中刪除zip文件中的條目:https://bugs.python.org/issue6818 更具體地說,我包含來自ubershmekel的zipfile.remove.2.patch
。 在對Python-2.7進行了一些修改之後,根據交付的單元測試,補丁工作得很好。Python從zip文件中刪除條目
但是,我遇到了一些問題,當刪除,添加和刪除+添加文件而不關閉之間的zip文件。
Error
Traceback (most recent call last):
File "/home/martin/git/pyCombineArchive/tests/test_zipfile.py", line 1590, in test_delete_add_no_close
self.assertEqual(zf.read(fname), data)
File "/home/martin/git/pyCombineArchive/combinearchive/custom_zip.py", line 948, in read
with self.open(name, "r", pwd) as fp:
File "/home/martin/git/pyCombineArchive/combinearchive/custom_zip.py", line 1003, in open
% (zinfo.orig_filename, fname))
BadZipFile: File name in directory 'foo.txt' and header 'bar.txt' differ.
意思是壓縮文件是好的,但不知何故中央詞典/條目標題會混淆。 這個單元測試重現此錯誤:
def test_delete_add_no_close(self):
fname_list = ["foo.txt", "bar.txt", "blu.bla", "sup.bro", "rollah"]
data_list = [''.join([chr(randint(0, 255)) for i in range(100)]) for i in range(len(fname_list))]
# add some files to the zip
with zipfile.ZipFile(TESTFN, "w") as zf:
for fname, data in zip(fname_list, data_list):
zf.writestr(fname, data)
for no in range(0, 2):
with zipfile.ZipFile(TESTFN, "a") as zf:
zf.remove(fname_list[no])
zf.writestr(fname_list[no], data_list[no])
zf.remove(fname_list[no+1])
zf.writestr(fname_list[no+1], data_list[no+1])
# try to access prior deleted/added file and prior last file (which got moved, while delete)
for fname, data in zip(fname_list, data_list):
self.assertEqual(zf.read(fname), data)
我修改壓縮文件模塊和完整單元測試文件可以在這個要點中找到:https://gist.github.com/FreakyBytes/30a6f9866154d82f1c3863f2e4969cc4