2012-01-17 119 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])