字节 - 从s3下载文件对象,但字节词为空
请参阅底部的更新 - 问题略有更改
我正在尝试使用boto3的.download_fileobj
方法将文件从S3下载到类似文件的对象,但是当我尝试检查时下载的字节词是空的。但是,我不确定我在做什么错:
client = boto3.client('s3')
data = io.BytesIO()
client.download_fileobj(Bucket='mybucket', Key='myfile.wav', Fileobj=data)
print(data.read())
哪个会产生一个空的bytestring:
b''
更新:
有点解决。因此,事实证明,data.seek(0)
在download_fileobj
line解决问题之后。 鉴于此,我现在正在寻找一个答案,以解释该片段的作用以及为什么解决问题。
See update at bottom - question slightly changed
I'm trying to download a file from s3 to a file-like object using boto3's .download_fileobj
method, however when I try to inspect the downloaded bytestream, it's empty. I'm not sure what I'm doing wrong however:
client = boto3.client('s3')
data = io.BytesIO()
client.download_fileobj(Bucket='mybucket', Key='myfile.wav', Fileobj=data)
print(data.read())
Which yields an empty bytestring:
b''
UPDATE :
kINDA SOLVED. So it turns out that adding data.seek(0)
after the download_fileobj
line solves the problem. In light of this, I am now looking for an answer that explains what this snippet does and why it fixes the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
谢谢您,我遇到了同样的问题。 :o)
此作用的原因是,文件缓冲对象可以用内部指针指向当前位置以读取或写入到的位置。
当您传递
read()
方法时,这一点很重要。当
client.download_fileobj()
写入字节流或任何操作写入任何流时,指针定位在上一篇文字的末尾。因此,您需要从刚写的内容的开头告诉文件缓冲对象。
Thank you for this, I was running into the same problem. :o)
The reason this works is that file buffer objects work with an internal pointer to the current spot to read from or write to.
This is important when you pass the
read()
method a number of bytes to read, or to continually write to the next section of the file.As the
client.download_fileobj()
writes to the byte stream, or any operation writes to any stream, the pointer is positioned to the end of the last write.So you need to tell the file buffer object that you want to read from the beginning of what was just written.