我想要解压缩不同目录中的文件,这些目录位于不同的路径中。并进行如下编码,错误为无效数据流。请帮帮我。非常感谢。
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)发布于 2013-06-06 21:59:17
Bz2.二进制数据的压缩/解压缩工作:
>>> 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)发布于 2013-06-06 21:36:55
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发布于 2013-06-06 21:50:37
这应该是可行的
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()))https://stackoverflow.com/questions/16963352
复制相似问题