2010-04-09 12 views
7

मैं इस कोड के साथ समस्या है:tmpfile और 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() 

मैं नहीं जानता क्यों यह कुछ भी प्रिंट आउट नहीं करता है। अगर मैं file.seek uncomment तो त्रुटि उत्पन्न होती है:

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 समस्या के लिए। इसे प्रारंभ करते समय मुझे कोई त्रुटि नहीं होती है। पायथन 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 

उत्तर

8

'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() 
+0

धन्यवाद! और tempfile इस रिपोर्ट नहीं करता है। शायद मुझे इसकी रिपोर्ट करनी चाहिए? –

+0

@Vojtech आर यह करता है। एक barebones 'fhandle = tempfile कोशिश करें। समकालीन फ़ाइल (मोड =' wrb ')' (यह एक OSError Errno22 अमान्य तर्क देता है ...) – ChristopheD

+0

@ क्रिस्टोफेड। मैंने प्रश्न में उदाहरण जोड़ा। .read() तक कोई त्रुटि नहीं है। –

संबंधित मुद्दे