问题描述
我有一个 Python 模块,它使用模块目录子目录中的一些资源.在搜索堆栈溢出并找到相关答案后,我设法通过使用类似
的东西将模块定向到资源导入操作系统os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf')
当我从其他地方调用模块时,这工作正常,但是当我在更改当前工作目录后调用模块时它会中断.问题是__file__
的内容是相对路径,没有考虑到我改目录的情况:
如何在 __file__
中编码绝对路径,或者除此之外,无论当前工作目录是什么,我如何访问模块中的资源?谢谢!
在模块最开始存放模块目录的绝对路径:
package_directory = os.path.dirname(os.path.abspath(__file__))
之后,根据这个package_directory
加载你的资源:
font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf')
毕竟,不要修改进程范围的资源,比如当前工作目录.在编写良好的程序中,从来没有真正需要更改工作目录,因此避免使用 os.chdir()
.
I have a Python module which uses some resources in a subdirectory of the module directory. After searching around on stack overflow and finding related answers, I managed to direct the module to the resources by using something like
import os
os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf')
This works fine when I call the module from elsewhere, but it breaks when I call the module after changing the current working directory. The problem is that the contents of __file__
are a relative path, which doesn't take into account the fact that I changed the directory:
>>> mymodule.__file__
'mymodule/__init__.pyc'
>>> os.chdir('..')
>>> mymodule.__file__
'mymodule/__init__.pyc'
How can I encode the absolute path in __file__
, or barring that, how can I access my resources in the module no matter what the current working directory is? Thanks!
Store the absolute path to the module directory at the very beginning of the module:
package_directory = os.path.dirname(os.path.abspath(__file__))
Afterwards, load your resources based on this package_directory
:
font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf')
And after all, do not modify of process-wide resources like the current working directory. There is never a real need to change the working directory in a well-written program, consequently avoid os.chdir()
.
这篇关于当 CWD 发生变化时,如何在 Python 模块中使用相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!