【问题标题】:Can't extract .xz files with python "tarfile.ReadError: file could not be opened successfully"无法使用 python 提取 .xz 文件“tarfile.ReadError:文件无法成功打开”
【发布时间】:2015-11-15 09:24:22
【问题描述】:

我需要使用 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,但我不确定现在该尝试什么。

【问题讨论】:

  • 不应该是:tarfile.open('file.xz')
  • .tar.xz 还是简单的.xz 文件?
  • @hjpotter92 是的,应该是。我的实际代码有''
  • @falsetru 它只是 .xz
  • 我遇到了类似的问题,但在互联网上没有找到任何答案,所以我解压缩并重新压缩了文件,解决了这个问题。

标签: python python-3.x tar xz


【解决方案1】:

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

【讨论】:

  • 啊,我明白了。我把它弄混了,因为this question 使用 tarfile 但我看到他们在哪里使用 tar.xz
  • @Qwertie,啊..我的另一个答案;)
  • 最后一个问题。提取后如何保存文件,因为 extractall('.') 不再有效。
  • @Qwertie,我更新了答案以包含它:以“写入”模式打开文件,并在那里写入内容。
猜你喜欢
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 2011-06-20
  • 2018-04-01
  • 2016-01-15
  • 1970-01-01
  • 2022-06-22
相关资源
最近更新 更多