python boto3写入S3导致空文件

ste*_*ell 1 python amazon-s3 amazon-web-services 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)
Run Code Online (Sandbox Code Playgroud)

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

moo*_*oot 5

Don't use plain open in python. it is anti-pattern and difficult to spot the mistake. Always use "with open()". When within the with context, python will close the file for you (and flush everything), so there is no surprises.

Please check this out 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)
Run Code Online (Sandbox Code Playgroud)