【问题标题】:tmpfile and gzip combination problemtmpfile和gzip组合问题
【发布时间】:2010-04-09 12:08:01
【问题描述】:

我对这段代码有疑问:

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

【问题讨论】:

    标签: python gzip base64


    【解决方案1】:

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

    【讨论】:

    • 谢谢!并且 tempfile 没有报告这一点。也许我应该报告这个?
    • @Vojtech R. 确实如此。尝试一个准系统fhandle=tempfile.TemporaryFile(mode='wrb')(它返回一个 OSError Errno22 Invalid argument...)
    • @ChristopheD。我在问题中添加了示例。 .read() 之前没有错误。
    • @Vojtech R:我无法在工作中重现这一点(Python 2.6,Windows)。可能是特定于操作系统的(今晚我会用 mac 进行检查)
    • @ChristopheD:所以我可以在 Python 2.5 上产生这种奇怪的行为,在 Python 2.6 上它会引发错误。
    【解决方案2】:

    一些提示:

    • 您不能在wrb 模式或wbw+b 下使用.seek(0).read() gzip 文件。 GzipFile 类 __init__ 仅通过查看 wrb 的第一个字符将自己设置为 READWRITE(在这种情况下将自己设置为 WRITE)。
    • 在执行f = gzip.GzipFile(mode='rb', fileobj=file) 时,您的真实文件是file 而不是f,在阅读GzipFile 类定义后我明白了。

    对我来说一个可行的例子是:

    from tempfile import NamedTemporaryFile
    
    import gzip
    
    
    with NamedTemporaryFile(mode='w+b', delete=True, suffix='.txt.gz', prefix='f') as t_file:
        gzip_file = gzip.GzipFile(mode='wb', fileobj=t_file)
        gzip_file.write('SOMETHING HERE')
        gzip_file.close()
        t_file.seek(0)
    
        # Do something here with your t_file, maybe send it to an external storage or:
        print t_file.read()
    

    我希望这对那里的人有用,我花了很多时间才使它起作用。

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2020-01-24
      相关资源
      最近更新 更多