2015-11-15 92 views
1

我需要使用python提取一些压缩为.xz文件的文本文件。无法用python提取.xz文件“tarfile.ReadError:文件无法成功打开”

我的代码只是

import tarfile 

tarfile.open('file.xz') 

但这种失败,我已经尝试了这许多.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文件没有被破坏,可以用gnome档案管理器打开。

我搜索了这个问题,发现this bug report,但我不确定现在要做什么。

+0

它不应该是:'tarfile.open('file.xz')' – hjpotter92

+1

是一个'.tar.xz'还是一个简单的'.xz'文件? – falsetru

+0

@ hjpotter92是的,应该是。我的实际代码有'' – Qwertie

回答

2

如果它不是一个.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) 
+0

啊,我明白了。我弄混了因为[这个问题](https://stackoverflow.com/questions/17217073/how-to-decompress-a-xz-file-which-has-multiple-folders-files-inside-in-a -singl)使用tarfile,但我看到他们在哪里使用tar.xz – Qwertie

+0

@Qwertie,啊..我的另一个答案;) – falsetru

+0

只是最后一个问题。如何在提取后保存文件,因为extractall('。')不再有效。 – Qwertie