IOError: [Errno 2] 没有此文件或目录,但文件确实存在
我总是收到一个输入输出错误,提示我的目录不存在。我到底做错了什么呢?
我在一个名为 pirate.py 的单独文件中写了这些代码:
with open("/images/image.jpg", "rb") as fin:
image_data = fin.read()
with open("pirate.py","wb") as fout:
fout.write("image_data="+repr(image_data))
然后在我的主文件中有这段代码:
from pirate import image_data
# Content-type declaration
print('Content-type: text/html\n')
def main():
print('<!doctype html><head><meta charset="utf-8">')
print('<style>html {background:url (data:image/gif;base64,' + pirate.image_data + ')
我想把一张图片编码成base64格式,然后在一个 .cgi 文件中用作背景。我确定我的其他代码是没问题的,那我这里到底错在哪里呢?
3 个回答
0
你用的repr不是你想要的,你说图片数据是base64格式……所以你需要把它转换成base64格式。
with open("pirate.py","wb") as fout:
fout.write("image_data="+base64.b64encode(image_data))
然后你还说了
from pirate import image_data
接着你把它引用成
pirate.image_data
但其实你应该直接引用成
image_data
可能还有其他问题,因为你展示的图片路径和你评论中的图片路径不一致。
0
试着使用绝对文件路径。或者使用根目录前缀,像这样:ROOT_PATH = os.path.dirname(os.path.realpath(file))
0
你的代码是这样的:
open("/images/image.jpg", "rb")
我怀疑开头的这个“/”可能是个问题。或者你的图片文件夹是在根目录下吗?