2016-05-02 34 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可以完全消除這個問題的可能性。真棒幫助 - 史蒂夫 –