折腾:
【已解决】Python 3中如何从二进制数据生成或打开url后返回文件类的对象供后续audioread去audio_open打开
期间,希望从此处已有的音频二进制数据,去生成文件类型的对象,以希望后续的audioread.audio_open可以正常打开。
所以对于之前的问题:
打开一个url,返回一个类似于文件的对象,以便于供后面的audioread.audio_open
此处的说法是:
直接用python3中用io.BytesIO(s)即可?
去试试
先去搞清楚,如何从gridfs对象中读取二进制数据出来
想要获取此处音频文件的二进制数据,即gridfs的二进制数据
直接用read
“read(size=-1)¶
Read at most size bytes from the file (less if there isn’t enough data).
The bytes are returned as an instance of str (bytes in python 3). If size is negative or omitted all data is read.
Parameters:
* size (optional): the number of bytes to read”
用read()即可,
去试试:
import io audioBinaryData = audioObj.read() audioFileLikeObj = io.BytesIO(audioBinaryData) # <_io.BytesIO object at 0x115964468> with audioread.audio_open(audioFileLikeObj) as audioFp:
结果:
return rawread.RawAudioFile(path) File "/Users/crifan/.local/share/virtualenvs/xxx-6RbmF4Wj/lib/python3.6/site-packages/audioread/rawread.py", line 61, in __init__ self._fh = open(filename, 'rb') TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO
再去试试:
audioBinaryData = audioObj.read() # audioFileLikeObj = io.BytesIO(audioBinaryData) # <_io.BytesIO object at 0x115964468> import StringIO audioFileLikeObj = StringIO.StringIO() audioFileLikeObj.write(audioBinaryData) with audioread.audio_open(audioFileLikeObj) as audioFp:
结果:
import StringIO ModuleNotFoundError: No module named 'StringIO'
【总结】
实际上此处的Python 3中,是可以通过:
import io audioBinaryData = audioObj.read() audioFileLikeObj = io.BytesIO(audioBinaryData)
得到对应的文件类型的对象的:
# <_io.BytesIO object at 0x115964468>
后续可以正常去像操作文件一样去操作这个io即可。
只不过对于此处特殊情况,去传入audioread.audio_open无法正常打开而已,所以只能去想其他办法了:
【已解决】Python 3中如何从二进制数据生成或打开url后返回文件类的对象供后续audioread去audio_open打开
注:python 2,才会有StringIO,对应写法:
import StringIO audioFileLikeObj = StringIO.StringIO() audioFileLikeObj.write(audioBinaryData)
转载请注明:在路上 » 【已解决】Python 3中通过二进制生成文件类型对象