Python程序教程

您现在的位置是:首页 >  Python

当前栏目

python解压bz2文件命令_解压缩bz2文件

bz2,文件,python,解压,命令,解压缩
2025-04-01 16:27:53 时间

大家好,又见面了,我是你们的朋友全栈君。

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)

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/135032.html原文链接:https://javaforall.cn