2012-01-17 7 views
4

Pythonを使用してbz2ファイルをダウンロードします。そして、私が使用してアーカイブを解凍します:Pythonでエラーが発生したときにUntarアーカイブ

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

はあなたがOS 'に渡すことを私たちにあなたがシェルで実行正確なコマンド、および(ファイル名を含む)正確なコマンドを示すことができましたシステム() '? – NPE

+0

'os.system'の代わりに[' subprocess.Popen'](http://docs.python.org/library/subprocess.html#replacing-os-system)を使用してください。 – jcollado

+0

どうやってファイルをダウンロードしていますか? unpackを呼び出す前にsleep(15)を入れても、それでも同じエラーが出ますか? – Foon

答えて

16

記録のために、python標準ライブラリには、tar、tar.bz2、およびtar.gz形式を自動的に処理するtarfileモジュールが付属しています。

さらに、ファイルリストを取得する、ファイルやディレクトリのサブセットを抽出する、またはアーカイブをチャンクしてストリーミング形式で処理することもできます(つまり、ファイル全体を解凍して解凍する必要はありません

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

それだこと..それは私がこのようにそれを行うだろう

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

ありがとう、tarfileモジュールについて知りませんでした。しかし、私はまだエラーがある理由を知りたい。 –

+0

'bzcat foo.tar.bz2> foo;の出力は何ですか?echo $?'いう?そして、tarファイルの実際の名前は何ですか? – synthesizerpatel

0

)小さなチャンク内のすべてを行います。 tar/withが残りの部分を処理します。

すべてのファイルへのパスを持つようにしたい:

import os 
filepaths = [] 
for (dirpath, dirnames, filenames) in walk(target_folder): 
    filepaths.extend([os.path.join(dirpath, f) for f in filenames]) 
関連する問題