以下代码给出了一个错误:
unpack需要一个长度为16的字节对象
https://docs.python.org/3.5/tutorial/stdlib2.html#brief-tour-of-the-standard-library-part-ii
11.3。使用二进制数据记录布局
import struct
with open('myfile.zip', 'rb') as f:
data = f.read()
start = 0
for i in range(3): # show the first 3 file headers
start += 14
fields = struct.unpack('<IIIHH', data[start:start+16])
crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
start += 16
filename = data[start:start+filenamesize]
start += filenamesize
extra = data[start:start+extra_size]
print(filename, hex(crc32), comp_size, uncomp_size)
start += extra_size + comp_size # skip to the next header
我这样创建'myfile.txt'(这可能是错的,但我还能做些什么?):
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
0001000100010001
...并将其压缩为'myfile.zip'。
结果是:
b'myfile.txt' 0xb52979e4 42 6818
b'' 0x79e448ab 2798889 446824448
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-7-d2e06ac7c75b> in <module>()
7 for i in range(3): # show the first 3 file headers
8 start += 14
----> 9 fields = struct.unpack('<IIIHH', data[start:start+16])
10 crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
11
error: unpack requires a bytes object of length 16
我知道'IIIHH'表示4个字节+4个字节+4个字节+ 2个字节+ 2个字节= 16个字节。但是,我不知道ZIP文件的结构。相同的代码对你们有用吗?我怎样才能做到这一点?
答案 0 :(得分:1)
此处的问题是代码尝试在zip中显示有关第一个三个文件的元数据,但您的zip只包含一个文件。
如果你改变了
for i in range(3): # show the first 3 file headers
到
for i in range(1):
它会起作用。