【问题标题】:How to create in-memory file object如何创建内存文件对象
【发布时间】:2017-06-21 09:45:35
【问题描述】:

我想制作一个内存文件以在 pygame 混音器中使用。我的意思是像 http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load 这样说 load() 方法支持文件对象。

import requests
from pygame import mixer

r = requests.get("http://example.com/some_small_file.mp3")
in_memory_file = file(r.content) # something like this
mixer.music.init()
mixer.music.load(in_memory_file)
mixer.music.play()

【问题讨论】:

    标签: python io


    【解决方案1】:

    您可能正在寻找来自 Python io 包的 BytesIOStringIO 类,它们都在 python 2python 3 中提供。它们提供了一个类似文件的界面,您可以在代码中使用与与真实文件交互完全相同的方式。

    StringIO用于存储文本数据:

    import io
    
    f = io.StringIO("some initial text data")
    

    BytesIO 必须用于二进制数据:

    import io
    
    f = io.BytesIO(b"\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01")
    

    要存储 MP3 文件数据,您可能需要 BytesIO 类。要将其从 GET 请求初始化到服务器,请执行以下操作:

    import requests
    from pygame import mixer
    import io
    
    r = requests.get("http://example.com/somesmallmp3file.mp3")
    inmemoryfile = io.BytesIO(r.content)
    
    mixer.music.init()
    mixer.music.load(inmemoryfile)
    mixer.music.play()
    
    # This will free the memmory from any data
    inmemoryfile.close()
    

    补充说明:由于这两个类都继承自IOBase,它们可以用作with 语句的上下文管理器,因此您不再需要手动调用close() 方法:

    import requests
    from pygame import mixer
    import io
    
    r = requests.get("http://example.com/somesmallmp3file.mp3")
    
    with io.BytesIO(r.content) as inmemoryfile:
        mixer.music.init()
        mixer.music.load(inmemoryfile)
        mixer.music.play()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-19
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      相关资源
      最近更新 更多