Python 如何在内存中创建文件对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44672524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:20:45  来源:igfitidea点击:

How to create in memory file object

pythonio

提问by Fatih K?l??

I want to make a in-memory file to use in pygame mixer. I mean something like that (http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.loadit says load() method supports file object)

我想制作一个在 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 that
mixer.music.init()
mixer.music.load(in_memory_file)
mixer.music.play()

回答by Antwane

You are probably looking for BytesIOor StringIOclasses from Python iopackage, both available in python 2and python 3. They provide a file-like interface you can use in your code the exact same way you interact with a real file.

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

StringIOis used to store textual data:

StringIO用于存储文本数据:

import io

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

BytesIOmust be used for binary data:

BytesIO必须用于二进制数据:

import io

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

To store MP3 file data, you will probably need the BytesIOclass. To initialize it from a GET request to a server, proceed like this:

要存储 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()