如何一次性解压包含多个文件夹/文件的.xz文件?

16

我想解压一个包含几个文件夹和文件的 .xz 文件,但是我没有找到使用 lzma 模块直接解压的方法。这是我看到的 decompress 方法:

In [1]: import lzma

In [2]: f = lzma.decompress("test.tar.xz")
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-2-3b08bf488f9d> in <module>()
----> 1 f = lzma.decompress("test.tar.xz")

error: unknown file format

还有其他方法可以解压缩这个文件,使其创建结果文件夹吗?

1个回答

34

Python 3.3

import tarfile

with tarfile.open('test.tar.xz') as f:
    f.extractall('.')

Python 2.7

需要在 Python 2.7 中使用 lzma

import contextlib
import lzma
import tarfile

with contextlib.closing(lzma.LZMAFile('test.tar.xz')) as xz:
    with tarfile.open(fileobj=xz) as f:
        f.extractall('.')

falsetru,我决定使用Python 3,因为tarfile具有内置的xz压缩支持。我决定不在Python 2.7中使用lzma。谢谢 :) - vimal
1
这在Python 3.6上对于一个带有xz扩展名的LZMA压缩文件对我不起作用。我猜它们不一定是tar文件?我得到了tarfile.ReadError: file could not be opened successfully。相反,我使用了https://dev59.com/HVgQ5IYBdhLWcg3w4n7z中的答案。`contents = lzma.open('file.xz').read()` - themaninthewoods
我现在意识到这不是原来的问题,但也许我的评论可以帮助其他犯同样错误的人。 - themaninthewoods
这不可能是Python2.7的全部。我安装了pyliblzma,但仍然出现“未知压缩类型'xz'”的错误提示。 - hek2mgl
1
不确定这是否适合在SO上讨论。我正在调查过程中。如果我发现了什么,我会告诉你的。 - hek2mgl
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接