views:

60

answers:

1

I have problem with this code:

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()

I dont know why it doesn't print out anything. If I uncomment file.seek then error occurs:

  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

Just for information this version works fine:

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

EDIT: For wrb problem. It doesn't give me an error when initialize it. 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
+3  A: 

'wrb' is not a valid mode.

This works fine:

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()
nosklo
Thanks! And tempfile doesn't report this. Maybe I should report this?
Vojtech R.
@Vojtech R. It does. Try a barebones `fhandle=tempfile.TemporaryFile(mode='wrb')` (it returns an OSError Errno22 Invalid argument...)
ChristopheD
@ChristopheD. I added example to question. No error until .read().
Vojtech R.
@Vojtech R: I can't reproduce this here at work (Python 2.6, Windows). May be OS specific (I'll check with a mac this evening)
ChristopheD
@ChristopheD: So this weird behavior I can produce on Python 2.5, on Python 2.6 it raise Error.
Vojtech R.