python - tmpfile 和 gzip 组合问题

标签 python gzip base64

我对这段代码有疑问:

file = tempfile.TemporaryFile(mode='wrb')
file.write(base64.b64decode(data))
file.flush()
os.fsync(file)
# file.seek(0)
f = gzip.GzipFile(mode='rb', fileobj=file)
print f.read()

我不知道为什么它不打印任何东西。如果我取消注释 file.seek 则会发生错误:

  File "/usr/lib/python2.5/gzip.py", line 263, in _read
    self._read_gzip_header()
  File "/usr/lib/python2.5/gzip.py", line 162, in _read_gzip_header
    magic = self.fileobj.read(2)
IOError: [Errno 9] Bad file descriptor

仅供引用,此版本运行良好:

x = open("test.gzip", 'wb')
x.write(base64.b64decode(data))
x.close()
f = gzip.GzipFile('test.gzip', 'rb')
print f.read()

编辑:对于 wrb 问题。初始化时它不会给我一个错误。 Python 2.5.2。

>>> t = tempfile.TemporaryFile(mode="wrb")
>>> t.write("test")
>>> t.seek(0)
>>> t.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 9] Bad file descriptor

最佳答案

'wrb' 不是有效模式。

这很好用:

import tempfile
import gzip

with tempfile.TemporaryFile(mode='w+b') as f:
    f.write(data.decode('base64'))
    f.flush()
    f.seek(0)
    gzf = gzip.GzipFile(mode='rb', fileobj=f)
    print gzf.read()

关于python - tmpfile 和 gzip 组合问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2607206/

相关文章:

Python 和一维谱 - 如何访问拟合文件中的数据

python - 在每个字符串的第四个索引中添加一个点

python - pandas df.mean 用于跨轴 0 的多索引

ruby - 在 Ruby 中将十六进制摘要转换为 base64

xml - 使用 CDATA 存储原始二进制流?

python - 如何在反向引用上应用函数?

java - 如何使用 GZIPInputStream 修复 EOF 读取错误

gzip - 我可以使用 zlib 解压缩 .NET GZipStream 吗?

c++ - 如何使用miniz创建一个可以用gzip解压的压缩文件?

php - 如何使用 Swift 将字符串加密为 base64 中的 sha1?