tarfile.ReadError: 文件无法成功打开

问题描述 投票:0回答:1

我有以下代码来打开 .tgz 文件,但我得到 tarfile.ReadError: file could not be opened successfully.

fp = tarfile.open('file.tgz', 'r')
print fp.list()
fp.close()

我可以使用“tar -xvzf file.tgz”提取这个档案。显然它与文件的创建方式有关,因为当我使用

file
比较两个不同的 .tgz 文件时,我发现了差异; file2.tgz 适用于这段代码。

$ file file.tgz 
file.tgz: gzip compressed data, from FAT filesystem (MS-DOS, OS/2, NT)

$ file file2.tgz 
file2.tgz: gzip compressed data, was "", last modified: Tue Aug 19 11:16:10 2014, max compression

知道为什么会发生这种情况,或者我如何修改 file.tgz 以便它与 tarfile 一起使用?

注意:我使用的是 Python 2.7.5.

python tarfile
1个回答
0
投票

在我的例子中,文件是 double 压缩的。我听从了Rob的建议尝试

gzip -l --verbose file.gz
,发现压缩比为负的关键提示

method  crc     date  time    compressed uncompressed  ratio uncompressed_name
defla 8448d70e Jul  1 11:34        11176        11146  -0.3% output.gz

运行

tar -xvf output.gz
未归档没有问题。但是 Python 的 tarfile 似乎认为它已损坏:

import tarfile
tarfile.open('output.gz', 'r:gz')  # throws invalid header error

那是因为 tar 似乎可以处理多级压缩。如果你解压一次,它应该可以工作:

import tarfile
import gzip
import shutil

with gzip.open('output.gz') as g:
    with open('output2.gz', 'wb') as f_out:
        shutil.copyfileobj(g, f_out)

tarfile.open('output2.gz', 'r:gz') # <tarfile.TarFile object at 0x109152690>

现在压缩比看起来正确:

gzip -l --verbose output*
method  crc     date  time    compressed uncompressed  ratio uncompressed_name
defla 8448d70e Jul  1 11:34        11176        11146  -0.3% output
defla 76e69d8c Jul  1 11:37        11146        44032  74.6% output2
© www.soinside.com 2019 - 2024. All rights reserved.