gpt4 book ai didi

python boto3 写入 S3 导致空文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:19 25 4
gpt4 key购买 nike

我在使用 Python 2.7 和 boto3 将文件写入 S3 存储桶时遇到问题。具体来说,当我在我的 EC2 实例上写入一个文件,关闭它,然后尝试将新文件写入 S3 存储桶时,我看到一个文件已写入,但它是空的(0 字节)。这是代码片段:

!/usr/bin/python

import boto3

newfile = open('localdestination','w')

newfile.write('ABCDEFG')

newfile.close

fnamebuck = 'bucketdestination'

client = boto3.client('s3')

inptstr = 'localdestination'

client.upload_file(inptstr, 'bucketname', fnamebuck)

我试过修改权限,在文件关闭后添加延迟,更改我的变量名,以及各种代码更改,但都无济于事。我没有收到任何错误消息。知道这个 S3 存储桶写入有什么问题吗?

最佳答案

不要在 python 中使用 plain open。它是反模式的,很难发现错误。始终使用“with open()”。在 with 上下文中时,python 将为您关闭文件(并刷新所有内容),因此不会有任何意外。

请查看 Not using with to open file

import boto3
inptstr = 'localdestination'
with open(inptstr,'w') as newfile:
newfile.write('ABCDEFG')

fnamebuck = 'bucketdestination'
s3 = boto3.client('s3')
s3.upload_file(inptstr, 'bucketname', fnamebuck)

关于python boto3 写入 S3 导致空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com