python - 无法使用 python 提取 .xz 文件 "tarfile.ReadError: file could not be opened successfully"

标签 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 存档管理器正常打开。

我搜索了这个问题,发现this bug report但我不知道现在该尝试什么。

最佳答案

如果不是.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)

关于python - 无法使用 python 提取 .xz 文件 "tarfile.ReadError: file could not be opened successfully",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718155/

相关文章:

python - 如何从python中的.tar存档中提取特定文件?

python - Pandas:根据多个其他列中的值填充空值

python - 过滤 Pandas 中特定日期范围的数据框

python - matplotlib 中的 TeX 渲染、大括号和字符串格式化语法

python-3.x - 如何从数据框中获取单个项目列表

python-3.x - CNN 的 TensorFlow Xavier 初始值设定项的 numpy 等价物是什么?

python - IE7 使用 jQuery 解析 JSON 抛出 "parseerror"

python - 如何在 python 中的两个列表之间获取 k-top 错误?

linux - Tar 当前目录中的 100 个目录

c++ - append 到 gzip 压缩的 Tar-Archive