我有一个文件,我需要逐块读入内存并压缩它。在
为此,我使用Zlib库。此库通过使用方法compressobj()
提供流式处理选项。在
def read_in_chunks(file_object, chunk_size=1024*2):
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
def compress_chunks(gen_obj):
for i in gen_obj:
compress = zlib.compressobj(2, zlib.DEFLATED, -15)
compressed_data = compress.compress(i)+compress.flush()
yield (compressed_data)
if __name__ == '__main__':
test_data = open('test.txt','rb')
chunk_input = read_in_chunks(test_data)
compressed_data = compress_chunks(chunk_input)
with open('test_zip_file.dat','wb') as ff:
for d in compressed_data:
ff.write(d)
f.close()
使用上面的代码,我可以将文件以压缩的方式写回文件中。在
但要把它读回去,我可以按照同样的程序来做。在
我需要把数据块读回内存解压并写回文件。在
我在将对象解压缩成块时面临以下问题
1)zlib: Error -3 while decompressing data: invalid distance too far back
:
当我试图通过添加zlib.decompress.flush()
为每个块创建新的解压缩对象时,就会发生这种情况
2)Loss of data
:
当我不为每个块创建新对象并尝试对多个块进行解压时,我得到的是一个空字符串,得到的数据比原始文件少。在
^{pr2}$
将压缩块写入文件时,没有任何分隔符。所以,当读回它进行解压时,程序无法解压压缩后的字符串。在
通过添加分隔符,我可以解压数据并检索实际数据。在
相关问题 更多 >
编程相关推荐