当 CWD 更改时,如何在 Python 模块中使用相对路径?
我有一个 Python 模块,它使用模块目录的子目录中的一些资源。在搜索堆栈溢出并找到相关答案后,我设法使用类似的方法将模块定向到资源。
import os
os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf')
当我从其他地方调用模块时,它工作得很好,但当我在更改当前工作目录后调用模块时,它会中断。问题是 __file__
的内容是相对路径,它没有考虑到我更改目录的事实:
>>> mymodule.__file__
'mymodule/__init__.pyc'
>>> os.chdir('..')
>>> mymodule.__file__
'mymodule/__init__.pyc'
How can I Encode the Absolute Path in __file__
>,或者除此之外,无论当前工作目录是什么,我如何访问模块中的资源?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在模块的最开始存储模块目录的绝对路径:
然后,根据这个
package_directory
加载资源:毕竟,不要修改进程范围的资源,例如当前工作目录。在编写良好的程序中,从来没有真正需要更改工作目录,因此避免使用 os.chdir()。
Store the absolute path to the module directory at the very beginning of the module:
Afterwards, load your resources based on this
package_directory
: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()
.基于 lunaryorn 的答案,我在模块的顶部保留了一个函数,我必须在其中构建多个路径。这节省了我重复输入
join
的时间。要构建路径,请像这样调用它:
或者如果您只需要包目录:
Building on lunaryorn's answer, I keep a function at the top of my modules in which I have to build multiple paths. This saves me repeated typing of
join
s.To build the path, call it like this:
Or if you just need the package directory: