2017-06-22 91 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: 

,它应该工作。