python boto3 写入 S3 导致空文件

标签 python amazon-web-services amazon-s3 boto3

我在使用 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/

相关文章:

mysql - 将表从 Amazon RDS 导出到 CSV 文件

python - 如何使用 django (python) 和 s3 上传文件?

python - 在Python中解析时间戳

python - 可扩展供应协议(protocol)实现?

amazon-web-services - 请求的 URL 返回错误 : 403, AWS Server less: Amplify app to CodeCommit

python - AWS Lambda 错误消息 "Unable to import module ' lambda_function' : No module named 'lambda_function' ",

r - 如何使用 aws.s3 包函数(write_using 和 read_using)从 EC2 上的 R 访问 S3 数据?

python - Django manytomany 关系超过 2 个应用程序

python - 如何修复 'django.db.utils.OperationalError: near "无“: syntax error' db. sqlite3?

amazon-web-services - 如何使用 CloudFormation 配置 CloudFront 将 'Headers' 中的 'ForwardedValues' 属性设置为 'all' ?