python - 在 Python 中解压存档有错误

标签 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)

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

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

但是我可以毫无问题地从 shell 中解压存档。

你知道我做错了什么吗?

最佳答案

郑重声明,python 标准库附带 tarfile自动处理 tar、tar.bz2 和 tar.gz 格式的模块。

此外,您还可以做一些有趣的事情,例如获取文件列表、提取文件或目录的子集或将存档分块,以便您以流式处理形式处理它(即您不必解压缩整个文件然后解压它。 . 它以小块的形式完成所有事情)

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

关于python - 在 Python 中解压存档有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8893359/

相关文章:

python - Sklearn LogisticRegressionCV 的类似数组的输入

python - 使用不同数量的变量进行查询

python - 从 Pandas 到字典,第一列中的值将是键,第二列中的相应值将全部在列表中

python - numpy 数组的最快保存和加载选项

python - Scrapy Xpath 构造在动态站点上生成空括号

python - Django:多个外键查找

python - 在 YARN 上运行 Spark 作业

python - 当我尝试在 Docker 容器中运行 shell 脚本时无法打开文件

python - Pandas 数据帧处理中的关键错误

python - 如何修改 .bash_profile 文件,以便无需输入文件路径即可运行 python 脚本?