2016-05-02 38 views
1

我对Python 2.7和boto3写入文件到S3存储桶存在问题。具体来说,当我写入EC2实例上的文件时,关闭它,然后尝试将新文件写入S3存储桶,我发现写入了一个文件,但它是空的(0字节)。下面的代码片段:python boto3向S3写入结果为空文件

!/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桶写入有什么问题?

回答

1

从你的代码好像你不调用close()函数,你缺少()

!/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) 
1

不要使用蟒蛇纯开。这是反模式,很难发现错误。始终使用“with open()”。在with context中,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) 
+0

感谢。同意Moot认为with open可以完全消除这个问题的可能性。真棒帮助 - 史蒂夫 –