16

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 ?

mgilson
  • 300,191
  • 65
  • 633
  • 696
vimal
  • 393
  • 1
  • 3
  • 11

1 Answers1

34

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('.')
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 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 :) – vimal Jun 22 '13 at 10:41
  • 1
    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 https://stackoverflow.com/questions/42079724/how-to-unpack-xz-file-with-python-which-contains-only-data-but-no-filename . `contents = lzma.open('file.xz').read()` – themaninthewoods Jul 06 '17 at 18:58
  • I now realize this is not the original question, but maybe my comment can help someone else who made the same mistake. – themaninthewoods Jul 06 '17 at 19:21
  • This can't be all for python2.7. I installed pyliblzma and I'm still getting `unknown compression type 'xz'` – hek2mgl Oct 23 '18 at 14:05
  • @hek2mgl, Could you post a separate question with traceback? – falsetru Oct 23 '18 at 15:15
  • 1
    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. – hek2mgl Oct 23 '18 at 17:58
  • @falsetru 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. – hek2mgl Oct 23 '18 at 18:30