我正在尝试解压缩文件进行一些更改,然后再次压缩它。解压缩似乎工作正常。我只需要一种方法来压缩它,以便它像以前一样被压缩。
这是我的代码:
import zlib
path = './input'
pathOut = './output'
def getInt(intArray):
summe = 0
for i in range(len(list(intArray))):
summe += intArray[i]*256**i
return(summe)
print(path)
inputfile = open(path, 'rb')
header = {}
header.update({"intro":inputfile.read(28)})
print("intro",(header["intro"]))
for key in ["header_size", "c_size", "header_v", "u_size", "blocks"]:
header.update({key:inputfile.read(4)})
print(key,getInt(header[key]))
inputfile.seek(getInt(header['header_size']))
blocks_count = getInt(header['blocks'])
data = []
for i in range(blocks_count):
block_header = {}
block_header.update({"c_size":inputfile.read(2)})
print("c_size",getInt(block_header["c_size"]))
block_header.update({"u_size":inputfile.read(2)})
print("u_size",getInt(block_header["u_size"]))
block_header.update({"checksum":inputfile.read(4)})
print("checksum",getInt(block_header["checksum"]))
temp = inputfile.read(getInt(block_header['c_size']))[2:-4]
data.append(zlib.decompressobj().decompress(b'x\x9c' + temp))
output = b''
inputfile.seek(0)
output = inputfile.read(getInt(header["header_size"]))
inputfile.close()
compressor = zlib.compressobj(1)
for block in data:
compressor.compress(block)
output += compressor.flush(zlib.Z_SYNC_FLUSH)
print("output length",len(output))
print("c_size",getInt(header["c_size"]))
outputFile = open(pathOut, 'wb')
outputFile.write(output)
outputFile.close()
当我尝试解压缩我的输出时,它说:
Traceback (most recent call last):
File "C:\Users\LSDesktop\Desktop\bla - Copy.py", line 45, in <module>
data.append(zlib.decompressobj().decompress(b'x\x9c' + temp))
zlib.error: Error -3 while decompressing data: invalid stored block lengths
这是前 50 个字节,包括第一个块的标头。它们应该是怎样的(在我压缩之前它们是怎样的):
b'B\x0c\x00 rWfyx\x01\xacY\tX\x14G\x16\xae\x9e)p\x00\r\x18\x15\xb9Lk\xc7\x03\xaf\x88\x1a\x8c\x0c\xa8\x084(\x82\x17\x87\x17\x88\xa3\x8c\x1c;r\x0b'
以及压缩后的前 50 个字节,包括第一个块的标头:
b'\xacY\tX\x14G\x16\xae\x9e)p\x00\r\x18\x15\xb9Lk\xc7\x03\xaf\x88\x1a\x8c\x0c\xa8\x084(\x82\x17\x87\x17\x88\xa3\x8c\x1c;r\x0b\x82&\nk4\x1c\x89fQ\x89'