字节 - 从s3下载文件对象,但字节词为空

发布于 2025-02-11 19:44:16 字数 536 浏览 2 评论 0原文

请参阅底部的更新 - 问题略有更改

我正在尝试使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鹤仙姿 2025-02-18 19:44:16

谢谢您,我遇到了同样的问题。 :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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文