【问题标题】:Decompress bz2 files解压bz2文件
【发布时间】:2013-06-06 13:25:31
【问题描述】:

我想解压位于不同路径的不同目录中的文件。 并且代码如下,错误是无效的数据流。请帮帮我。非常感谢。

import sys
import os
import bz2
from bz2 import decompress

path = "Dir"
for(dirpath,dirnames,files)in os.walk(path):
   for file in files:
       filepath = os.path.join(dirpath,filename)
       newfile = bz2.decompress(file)
       newfilepath = os.path.join(dirpath,newfile)

【问题讨论】:

  • 看起来您的一些变量在该代码中混杂了。否则,the documentation 表示解压缩需要数据,而不是文件名:bz2.decompress(data)

标签: python compression


【解决方案1】:

bz2.compress/decompress 处理二进制数据:

>>> import bz2
>>> compressed = bz2.compress(b'test_string')
>>> compressed
b'BZh91AY&SYJ|i\x05\x00\x00\x04\x83\x80\x00\x00\x82\xa1\x1c\x00 \x00"\x03h\x840"
P\xdf\x04\x99\xe2\xeeH\xa7\n\x12\tO\x8d \xa0'
>>> bz2.decompress(compressed)
b'test_string'

简而言之 - 您需要手动处理文件内容。如果您有非常大的文件,您应该更喜欢使用bz2.BZ2Decompressor 而不是bz2.decompress,因为后者要求您将整个文件存储在一个字节数组中。

for filename in files:
    filepath = os.path.join(dirpath, filename)
    newfilepath = os.path.join(dirpath,filename + '.decompressed')
    with open(newfilepath, 'wb') as new_file, open(filepath, 'rb') as file:
        decompressor = BZ2Decompressor()
        for data in iter(lambda : file.read(100 * 1024), b''):
            new_file.write(decompressor.decompress(data))

您还可以使用bz2.BZ2File 来简化此操作:

for filename in files:
    filepath = os.path.join(dirpath, filename)
    newfilepath = os.path.join(dirpath, filename + '.decompressed')
    with open(newfilepath, 'wb') as new_file, bz2.BZ2File(filepath, 'rb') as file:
        for data in iter(lambda : file.read(100 * 1024), b''):
            new_file.write(data)

【讨论】:

    【解决方案2】:

    bz2.decompress 获取压缩的数据并对其进行膨胀。您传递的是文件名,而不是文件中的数据!

    改为这样做:

    zipfile = bz2.BZ2File(filepath) # open the file
    data = zipfile.read() # get the decompressed data
    newfilepath = filepath[:-4] # assuming the filepath ends with .bz2
    open(newfilepath, 'wb').write(data) # write a uncompressed file
    

    【讨论】:

    • 仍然存在错误文件未准备好写入谢谢
    【解决方案3】:

    这应该可以工作

    for file in files:
        archive_path = os.path.join(dirpath,filename)
        outfile_path = os.path.join(dirpath, filename[:-4])
        with open(archive_path, 'rb') as source, open(outfile_path, 'wb') as dest:
            dest.write(bz2.decompress(source.read()))
    

    【讨论】:

    • 以 open(archive_path, 'rb') 为源,open(outfile_path, 'wb') 为 dest: ^ SyntaxError: invalid syntax .There is still an error.非常感谢
    • 这是 python3 语法。试试:from __future__ import with_statement。如果这仍然不起作用,请分两步打破ẁith 语句,就像在 Juraj Ivančić 的回答中一样
    • 太晚了——在看到你的回复后,我改变了我的使用链式语句。不知道,谢谢!
    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多