Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 352
jvkersch Avatar asked Nov 15 '10 17:11

jvkersch


People also ask

How do you access the relative path in Python?

path. relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path.

What is path CWD ()?

In Pathlib, the Path. cwd() function is used to get the current working directory and / operator is used in place of os. path. join to combine parts of the path into a compound path object. The function nesting pattern in the os.


1 Answers

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().

like image 119
lunaryorn Avatar answered Oct 13 '22 10:10

lunaryorn