2

I've written some code to bz2-compress a file with the BZ2 Compressor Object:

def compressFile(file_name, new_name):      
    comp = bz2.BZ2Compressor()
    comFile = open(new_name, "wb")
    oldFile = open(file_name, "rb")
    while True:
        data = oldFile.read(1024*1024)
        if(len(data) == 0):
            break
        compressed = comp.compress(data)
        comFile.write(compressed)
    comp.flush()
    comFile.close()

I don't get an error and the file is created, but when I want to open it with an archive manager, I get a nonspecific error. I can't find my mistake and this module is poorly documented.

4

1 回答 1

5

当您使用 aBZ2Compressor时,您在调用时获取数据块compress(),并且很有可能您仅在调用时获取数据flush()

如果您像这样更改功能,它应该可以工作:

def compressFile(file_name, new_name):      
    comp = bz2.BZ2Compressor()
    comFile = open(new_name, "wb")
    oldFile = open(file_name, "rb")
    while True:
        data = oldFile.read(1024*1024)
        if(len(data) == 0):
            break
        comFile.write(comp.compress(data))
    comFile.write(comp.flush())
    comFile.close()
于 2012-11-18T21:55:49.423 回答