【发布时间】:2018-06-11 08:08:31
【问题描述】:
我想编写一个返回字符串而不是字节的函数。
功能:
def read_image(path):
with open(path, "rb") as f:
data = f.read()
return data
image_data = read_image("/home/user/icon.jpg")
如何将值image_data 转换为类型str。
如果转换为字符串成功,如何将字符串重新转换为字节。
【问题讨论】:
-
那么你为什么不能把
str()应用到你想要返回的任何东西上呢? -
.decode("utf-8")
-
@Primusa,
.decode("utf-8") 抛出异常。 UnicodeDecodeError:'utf-8' codec can't decode byte 0xff -
我不认为您可以从 jpg 图像中创建字符串。你打算用它做什么?
-
为了适配 Python 2。一些库使用我的函数,但库是用 Python 2 编写的。@PatrickHaugh
标签: python python-3.x