无法使用python" tarfile提取.xz文件.ReadError:文件无法成功打开"

时间:2015-11-15 09:24:23

标签: python python-3.x tar xz

我需要使用python提取一些压缩为.xz文件的文本文件。

我的代码只是

import tarfile 

tarfile.open('file.xz')

但是失败并出现错误

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

我在许多.xz文件上尝试了这个并得到了相同的结果。 .xz文件没有损坏,可以使用gnome archive manager打开。

我搜索了问题并找到this bug report,但我不确定现在要尝试什么。

1 个答案:

答案 0 :(得分:4)

如果它不是.tar.xz文件,而是.xz文件,则需要使用lzma module,而不是tarfile模块:

import lzma

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

保存提取的内容:

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