2017-06-22 93 views
0

我想編碼某個文件夾中的文件並創建一個base64字符串。我可以加載文件並讀取()它,但創建base64字符串不會打印任何內容。Python打開圖像文件和編碼到base64是空的

for file in os.listdir(os.path.join(app.config['UPLOAD_FOLDER'])): 
    print file 
    print type(file) 
    if file.startswith(str(current_user.id)): 
      with open(file, 'rb') as thefile:       
       data = thefile.read().encode("base64") 
       print "base: ", data 
       print "the ", type(thefile) 

這裏是打印:

1-bild-1.jpg 
<type 'str'> 
base: 
the <type 'file'> 

編輯:

我注意到,thefile.read()是空以及。打印什麼都沒顯示

+1

您確定要打開正確的文件嗎?嘗試'open(os.path.join(app.config ['UPLOAD_FOLDER'],file))'。 –

+0

是的,它告訴我文件和atm的正確名稱。目錄中只有一個文件可以打開並查看。 – Roman

+1

你只是想打開文件「1-bild-1.jpg」...... Python應該如何知道該文件在哪個文件夾中?你需要加入文件夾路徑。 – deceze

回答

1

您必須指定打開的完整文件路徑,而不僅僅是文件名。

變化

with open(file, 'rb') as thefile: 

with open(os.path.join(app.config['UPLOAD_FOLDER'], file), 'rb') as thefile: 

,它應該工作。