2015-11-15 100 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