Python FileNotFoundError 即使文件存在

Python FileNotFoundError even if the File is there

我的项目目录树是这样的,

build
----fonts
--------Roboto Bold.ttf
----main.py

以下代码错误,

from pyglet import font
font.add_file("fonts\Roboto Bold.ttf")

也试过这个代码,

import os
from pyglet import font
font.add_file(str(os.getcwd())+"\fonts\Roboto Bold.ttf")

错误是,

Traceback (most recent call last):
  File "{full_dir_name}\build\main.py", line 25, in <module>
    font.add_file(str(os.getcwd())+'\fonts\Roboto Bold.ttf')
  File "C:\python-3.8.5-amd64\lib\site-packages\pyglet\font\__init__.py", line 183, in add_file
    font = open(font, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '{full_dir_name}\fonts\Roboto Bold.ttf'

我已经尝试了大约一天,也看到了这里的其他帖子,但无法解决...

资源(图像、字体、声音等)文件路径必须相对于当前工作目录。工作目录可能与 python 文件的目录不同。

文件名和路径可以通过__file__. The current working directory can be get by os.getcwd(). If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join())相对文件路径获取。例如:

font.add_file(str(os.getcwd())+"\fonts\Roboto Bold.ttf")

font.add_file(os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts/Roboto Bold.ttf"))