使用gzip,tell()返回未压缩文件中的偏移量.
为了显示进度条,我想知道文件的原始(未压缩)大小.
有一个简单的方法可以找到答案吗?
Bri*_*sey 16
未压缩的大小存储在gzip文件的最后4个字节中.我们可以读取二进制数据并将其转换为int.(这仅适用于4GB以下的文件)
import struct
def getuncompressedsize(filename):
with open(filename, 'rb') as f:
f.seek(-4, 2)
return struct.unpack('I', f.read(4))[0]
Run Code Online (Sandbox Code Playgroud)
Jor*_*eña 13
该gzip格式指定字段名为ISIZE认为:
它包含原始(未压缩)输入数据模2 ^ 32的大小.
在gzip.py中,我假设你正在使用gzip支持,有一个被_read_eof定义的方法如下:
def _read_eof(self):
# We've read to the end of the file, so we have to rewind in order
# to reread the 8 bytes containing the CRC and the file size.
# We check the that the computed CRC and size of the
# uncompressed data matches the stored values. Note that the size
# stored is the true file size mod 2**32.
self.fileobj.seek(-8, 1)
crc32 = read32(self.fileobj)
isize = U32(read32(self.fileobj)) # may exceed 2GB
if U32(crc32) != U32(self.crc):
raise IOError, "CRC check failed"
elif isize != LOWU32(self.size):
raise IOError, "Incorrect length of data produced"
Run Code Online (Sandbox Code Playgroud)
在那里,您可以看到ISIZE正在读取该字段,但仅用于将其与self.size错误检测进行比较.这应该意味着GzipFile.size存储实际的未压缩大小.但是,我认为它没有公开曝光,所以你可能不得不入侵它以暴露它.不太确定,抱歉.
我现在只看了所有这些,我没有尝试过,所以我错了.我希望这对你有用.对不起,如果我误解了你的问题.
不管其他答案怎么说,最后四个字节并不是获取 gzip 文件未压缩长度的可靠方法。首先,gzip 文件中可能有多个成员,因此只有最后一个成员的长度。其次,长度可能超过4 GB,在这种情况下,最后四个字节代表长度模2 32。不是长度。
但是对于你想要的,没有必要获得未压缩的长度。相反,您可以将进度条基于消耗的输入量,而不是很容易获得的 gzip 文件的长度。对于典型的同质数据,该进度条将显示与基于未压缩数据的进度条完全相同的内容。
Unix 方式:通过 subprocess.call / os.popen 使用“gunzip -l file.gz”,捕获并解析其输出。