Python 打开图像文件并编码为 base64 为空

Python open image file and encode to base64 is empty

我正在尝试对某个文件夹中的文件进行编码并创建一个 base64 字符串。我可以加载文件并对其进行 read(),但创建 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() 也是空的。打印什么也没显示。

您必须指定要打开的完整文件路径,而不仅仅是文件名。

改变

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

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

它应该可以工作。