tmpfile和gzip组合问题

Voj*_*lko 8 python base64 gzip

我有这个代码的问题:

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

我不知道它为什么不打印任何东西.如果我取消注释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
Run Code Online (Sandbox Code Playgroud)

仅供参考,此版本可以正常工作:

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

编辑:对于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
Run Code Online (Sandbox Code Playgroud)

nos*_*klo 11

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