How to decompress a .xz file which has multiple folders/files inside, in a single go?
Asked Answered
P

1

17

I'm trying to uncompress a .xz file which has a few foders and files inside. I don't see a direct way to do this using lzma module. This is what I'm seeing for a decompress method :

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

Are there any other methods to un-compress this file so that it will create the resultant folder ?

Patrick answered 20/6, 2013 at 14:59 Comment(0)
A
36

Python 3.3

import tarfile

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

Python 2.7

Need lzma in Python 2.7

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('.')
Aventine answered 20/6, 2013 at 15:20 Comment(7)
falsetru, I decided to use Python 3 since tarfile has inbuilt support for xz compression. I decided not to use lzma in Python 2.7. Thank you :)Patrick
This didn't work for me in Python 3.6 on a LZMA compressed file with the xz extension. I guess they're not necessarily tar files? I get tarfile.ReadError: file could not be opened successfully . Instead, I used the answer from #42080224 . contents = lzma.open('file.xz').read()Plugugly
I now realize this is not the original question, but maybe my comment can help someone else who made the same mistake.Plugugly
This can't be all for python2.7. I installed pyliblzma and I'm still getting unknown compression type 'xz'Adder
@hek2mgl, Could you post a separate question with traceback?Aventine
Not sure if that would be on-topic on SO. I'm in the process of investigation. If I find something I'll let you know.Adder
@Aventine I think your answer says it. tarfile.open('filename', 'r:xz') can't be used in python2.7. I was hoping that this would be possible by installing the lzma module. I have to install python 2.7 packages via pip and http://.../package.tar.xz links and pip is calling tarfile.open() directly which fails with unknown compression error.Adder

© 2022 - 2024 — McMap. All rights reserved.