python 2.7 : Compressing data with the XZ format using the "lzma" module

标签 python checksum lzma xz

我正在试验 Python 2.7.6 中的 lzma 模块,看看我是否可以使用 XZ 格式创建压缩文件,供将来使用它的项目使用。我在实验中使用的代码是:

import lzma as xz

in_file = open('/home/ki2ne/Desktop/song.wav', 'rb')
input_data = in_file.read()

compressed_data = xz.compress(input_data)
out_file = open('/home/ki2ne/Desktop/song.wav.xz', 'wb')
in_file.close()
out_file.close()

而且我注意到与我使用纯 xz 时相比,结果文件有两个不同的校验和(MD5 和 SHA256)(尽管我可以使用任何一种方法解压缩 - 两个文件的解压缩版本的校验和相同).这会有问题吗?

更新:我通过 peterjc 的 Git 存储库(link here)安装反向端口(从 Python 3.3)找到了修复程序,现在它显示相同的校验和。不确定它是否有帮助,但我确保未安装存储库中的 LZMA Python 模块以避免可能的名称冲突。

这是我的测试代码来确认这一点:

# I have created two identical text files with some random phrases

from subprocess import call
from hashlib import sha256
from backports import lzma as xz

f2 = open("test2.txt" , 'rb')
f2_buf = buffer(f2.read())
call(["xz", "test1.txt"])

f2_xzbuf = buffer(xz.compress(f2_buf))
f1 = open("test1.txt.xz", 'rb')
f1_xzbuf = buffer(f1.read())

f1.close(); f2.close()

f1sum = sha256(); f2sum = sha256()

f1sum.update(f1_xzbuf); f2sum.update(f2_xzbuf)

if f1sum.hexdigest() == f2sum.hexdigest():
    print "Checksums OK"
else:
    print "Checksum Error"

我也使用常规的 sha256sum 验证了它(当我将数据写入文件时)。

最佳答案

我不会担心压缩文件中的差异 - 根据 .xz 文件中使用的容器格式和校验和类型,压缩数据可能会有所不同,但不会影响内容。

编辑 我一直在进一步研究这个问题,并编写了这个脚本来测试 PyLZMA Python2.x 模块和 lzma Python3.x 内置模块

from __future__ import print_function
try:
    import lzma as xz
except ImportError:
    import pylzma as xz
import os

# compress with xz command line util
os.system('xz -zkf test.txt')

# now compress with lib
with open('test.txt', 'rb') as f, open('test.txt.xzpy', 'wb') as out:
    out.write(xz.compress(bytes(f.read())))

# compare the two files
from hashlib import md5

with open('test.txt.xz', 'rb') as f1, open('test.txt.xzpy', 'rb') as f2:
    hash1 = md5(f1.read()).hexdigest()
    hash2 = md5(f2.read()).hexdigest() 
    print(hash1, hash2)
    assert hash1 == hash2

这会使用 xz 命令行实用程序和 Python 模块压缩文件 test.txt 并比较结果。在 Python3 下,lzma 产生与 xz 相同的结果,但在 Python2 下,PyLZMA 产生不同的结果,无法使用 xz 命令行实用程序提取。

您使用的是什么模块,在 Python2 中称为“lzma”?您使用什么命令来压缩数据?

编辑 2 好的,我找到了 Python2 的 pyliblzma 模块。然而,它似乎使用 CRC32 作为默认校验和算法(其他人使用 CRC64)并且有一个错误阻止更改校验和算法 https://bugs.launchpad.net/pyliblzma/+bug/1243344

您可以尝试使用 xz -C crc32 进行压缩以比较结果,但我仍然无法使用 Python2 库制作有效的压缩文件。

关于 python 2.7 : Compressing data with the XZ format using the "lzma" module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22370068/

相关文章:

python - 循环中的 lxml.etree._Element.append() 未按预期工作

python - 生成文件的 MD5 校验和

c - 两个结构的 TCP 校验和

java - 在 Java 中解压缩包含多个文件和目录的 7zip 存档

尝试解压缩时 Python LZMA Corrupt data error

python - matplotlib 'bar'与 'barh'情节。 bar的问题

python - 使用 scikit-learn python 的线性 SVM 时出现 ValueError

python - Mac OSX 10.7.4 上的 pygame 错误

c++ - 制作自定义自解压器