2012-01-17 114 views
4

我使用Python下載了bz2文件。然後我想用來解包:在Python中解壓縮出錯

def unpack_file(dir, file): 
    cwd = os.getcwd() 
    os.chdir(dir) 
    print "Unpacking file %s" % file 
    cmd = "tar -jxf %s" % file 
    print cmd 
    os.system(cmd) 
    os.chdir(cwd) 

不幸的是這與錯誤結束:

bzip2: Compressed file ends unexpectedly; 
    perhaps it is corrupted? *Possible* reason follows. 
bzip2: Inappropriate ioctl for device 
    Input file = (stdin), output file = (stdout) 

It is possible that the compressed file(s) have become corrupted. 
You can use the -tvv option to test integrity of such files. 

You can use the `bzip2recover' program to attempt to recover 
data from undamaged sections of corrupted files. 

tar: Nieoczekiwany EOF w archiwum 
tar: Nieoczekiwany EOF w archiwum 
tar: Error is not recoverable: exiting now 

但是我可以從解包殼歸檔,沒有任何問題。

你有什麼想法我做錯了嗎?

+1

你能告訴我們你在shell中運行的確切命令,確切的命令(包括文件名),你傳遞給'OS 。系統()'? – NPE 2012-01-17 10:57:53

+0

請使用['subprocess.Popen'](http://docs.python.org/library/subprocess.html#replacing-os-system)而不是'os.system'。 – jcollado 2012-01-17 11:14:54

+0

你是如何下載文件的?如果你在解壓縮之前先進入睡眠(15),那麼是否仍然有相同的錯誤? – Foon 2012-01-17 20:29:21

回答

16

據瞭解,python標準庫附帶tarfile模塊,該模塊可自動處理tar,tar.bz2和tar.gz格式。

此外,您可以做很多漂亮的事情,例如獲取文件列表,提取文件或目錄的子集或塊,以便以流形式處理它(即,您不必解壓整個文件然後解壓縮它..它在一小塊一小塊的一切)

import tarfile 
tar = tarfile.open("sample.tar.gz") 
tar.extractall() 
tar.close() 
+0

謝謝,不知道tarfile模塊。但是我仍然想知道爲什麼會出現錯誤。 – 2012-01-17 11:03:54

+0

'bzcat foo.tar.bz2> foo; echo $?'的輸出是什麼說?什麼是tar文件的實際名稱? – synthesizerpatel 2012-01-17 12:07:38

0

我會做這樣的:

import tarfile 
target_folder = '.' 
with tarfile.open("sample.tar.gz") as tar: 
    tar.extractall(target_folder) 

就是這樣。 tar/with照顧其餘。

如果你想有路徑的所有文件:

import os 
filepaths = [] 
for (dirpath, dirnames, filenames) in walk(target_folder): 
    filepaths.extend([os.path.join(dirpath, f) for f in filenames])