我需要使用 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/