Python中的Untar存档有错误

Szy*_*ski 4 python

我使用Python下载了一个bz2文件.然后我想用以下方法解压缩档案:

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)
Run Code Online (Sandbox Code Playgroud)

不幸的是,这以错误结束:

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
Run Code Online (Sandbox Code Playgroud)

但是,我可以从shell解压缩存档没有任何问题.

你有什么想法我做错了吗?

syn*_*tel 16

为了记录,python标准库附带了tarfile模块,该模块自动处理tar,tar.bz2和tar.gz格式.

此外,你可以做一些漂亮的事情,比如获取文件列表,提取文件或目录的子集,或者对存档进行分块,以便你以流形式处理它(即你不必解压缩整个文件然后解压它..它确实一切都在小块)

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
Run Code Online (Sandbox Code Playgroud)