我在网上发现了很多类似的问题,但我不确定它们是否能解决我的问题。我正在编写具有该结构的 Python 模块:
mymodule
|--- __init__.py
|--- resources
|—-- myfont.ttf
|--- ...
使用pygame,需要加载一个字体文件。所以我的
__init__.py
文件是这样开始的:
import os
import pygame
os.chdir(os.path.dirname(__file__)) # change working directory to use resources/myfont.ttf
pygame.init() # init the pygame module
font = pygame.font.Font("./resources/myfont.ttf", 10) # load myfont.ttf with size 10
问题是我想将工作目录更改回导入模块的位置,因为某些功能可能,例如,将图片保存到工作目录,我模块的用户不必深入研究我的模块文件来找到那张照片。
我应该用类似的东西把它改回来吗
import sys
os.chdir(os.path.dirname(sys.argv[0]))
每次我再次需要我自己的一些文件时都要重做整个操作?难道没有更简单的方法吗?
编辑:感谢Brian,方法是
from importlib.resources import files
import pygame
font_traversable = file("mymodule.resources").joinpath("myfont.ttf")
pygame.init()
font = pygame.font.Font(font_traversable, 10)