Search code examples
pythonpython-3.xtarxz

Can't extract .xz files with python "tarfile.ReadError: file could not be opened successfully"


I need to extract some text files compressed to .xz files using python.

My code is just

import tarfile 

tarfile.open('file.xz')

But this fails with the error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/tarfile.py", line 1558, in open
    raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully

I have tried this on many .xz files and got the same result. The .xz files are not broken and can be opened fine with gnome archive manager.

I searched the problem and found this bug report but I'm not sure what to try now.


Solution

  • If it's not a .tar.xz file, but a .xz file, you need to use lzma module, not tarfile module:

    import lzma
    
    with lzma.open("file.xz") as f:
        file_content = f.read()
    

    To save the extracted content:

    with lzma.open("file.xz") as f, open('extracted', 'wb') as fout:
        file_content = f.read()
        fout.write(file_content)