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
How to create in memory file object
提问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 BytesIO
or StringIO
classes from Python io
package, 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包中的BytesIO
或StringIO
类io
,它们都在python 2和python 3 中可用。它们提供了一个类似文件的界面,您可以在代码中使用与与真实文件交互完全相同的方式。
StringIO
is used to store textual data:
StringIO
用于存储文本数据:
import io
f = io.StringIO("some initial text data")
BytesIO
must 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 BytesIO
class. 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()