How do I use a relative path in a Python module when the CWD has changed? -


i have python module uses resources in subdirectory of module directory. after searching around on stack overflow , finding related answers, managed direct module resources using

import os os.path.join(os.path.dirname(__file__), 'fonts/myfont.ttf') 

this works fine when call module elsewhere, breaks when call module after changing current working directory. problem contents of __file__ relative path, doesn't take account fact changed directory:

>>> mymodule.__file__ 'mymodule/__init__.pyc' >>> os.chdir('..') >>> mymodule.__file__ 'mymodule/__init__.pyc' 

how can encode absolute path in __file__, or barring that, how can access resources in module no matter current working directory is? thanks!

store absolute path module directory @ beginning of module:

package_directory = os.path.dirname(os.path.abspath(__file__)) 

afterwards, load resources based on package_directory:

font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf') 

and after all, not modify of process-wide resources current working directory. there never real need change working directory in well-written program, consequently avoid os.chdir().


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -