【问题标题】:IOError: [Errno 2] No such file or directory, but file does existIOError: [Errno 2] 没有这样的文件或目录,但文件确实存在
【发布时间】:2014-07-28 04:26:45
【问题描述】:

我不断收到一个 IO 错误,指出我的目录不存在。我做错了什么?

我将它保存在一个名为 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 中的背景,我确定我的其余代码都可以正常工作,我在这里做错了什么?

【问题讨论】:

  • 能否提供完整的追溯?
  • 运行时可能不在正确的目录中。
  • 您能否更详细地说明您的目录结构? pirate.py 相对于您执行主脚本的位置在哪里?
  • Full tr​​aceback = IOError: [Errno 2] No such file or directory: 'server.csmcis.net/~ahatfiel/images/tinyPirate.jpg'
  • pirate.py 和主脚本都在/cgi-bin/

标签: python io cgi


【解决方案1】:

尝试使用绝对文件路径。或使用根前缀 ROOT_PATH = os.path.dirname(os.path.realpath(file))

【讨论】:

  • 我在代码中使用了完整路径,但我在这里将其编辑为 images/image.jpg。不过我会尝试其他解决方案。
  • 可能是权限问题?
【解决方案2】:

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     

可能还有其他一些问题,因为您显示的图像图像路径不是您评论中的图像路径

【讨论】:

    【解决方案3】:

    你的代码说

    open("/images/image.jpg", "rb")
    

    我怀疑开头的“/”是问题所在。还是您的图像文件夹在您的根目录中?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多