解决fp = builtins.open(filename, “w+b“)FileNotFoundError: [Errno 2] No such file or directory:

Posted 沉迷单车的追风少年

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决fp = builtins.open(filename, “w+b“)FileNotFoundError: [Errno 2] No such file or directory:相关的知识,希望对你有一定的参考价值。

项目场景:

三维草图生成训练


问题描述:

Traceback (most recent call last):
  File "sketch_gcn.py", line 392, in <module>
    model.train(epoch)
  File "sketch_gcn.py", line 264, in train
    self.conditional_generation(epoch)
  File "sketch_gcn.py", line 344, in conditional_generation
    make_image(sequence, epoch)
  File "sketch_gcn.py", line 155, in make_image
    pil_image.save(name, "JPEG")
  File "/root/anaconda3/envs/dpm-pc-gen/lib/python3.7/site-packages/PIL/Image.py", line 2169, in save
    fp = builtins.open(filename, "w+b")
FileNotFoundError: [Errno 2] No such file or directory: './model_save/500_output_.jpg'

原因分析:

PIL保存模型的时候,如果代码里的目录不存在,PIL不会自动创建目录,也不会主动抛出异常。


解决方案:

1、代码里加上异常处理,打印出异常,这样程序就不会崩。

    pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(),
                                    canvas.tostring_rgb())
    name = f"./model_save/" + str(epoch) + name + '.jpg'
    print("pil_image_save name by wangqiang", name)
    try:
        pil_image.save(name, "JPEG")
    except Exception as e:
        print("pil_image_save save error", e)

2、创建相应目录

mkdir model_save

以上是关于解决fp = builtins.open(filename, “w+b“)FileNotFoundError: [Errno 2] No such file or directory:的主要内容,如果未能解决你的问题,请参考以下文章

第四次作业

如何将文件指针 ( FILE* fp ) 转换为文件描述符 (int fd)?

C语言文件复制

关于变量类型FILE简要说明C

关于变量类型FILE简要说明C

下面的程序在devc++中出现了段错误,可能是非法访问内存,该怎样解决