I'm trying to add a directory to PATH wit code like this:
PROJECT_DIR = Path(__file__).parents[2]
sys.path.append(
PROJECT_DIR / 'apps'
)
It doesn't work. If I do print sys.path
I see something like this:
[..., PosixPath('/opt/project/apps')]
How should I fix this code? Is it normal to write str(PROJECT_DIR / 'apps')
?
The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.
append(mod_directory) to append the path and then open the python interpreter, the directory mod_directory gets added to the end of the list sys. path. If I export the PYTHONPATH variable before opening the python interpreter, the directory gets added to the start of the list.
Create Directory in Python Using the Path. mkdir() Method of the pathlib Module. The Path. mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True .
The Pathlib module in Python deals with path related tasks, such as constructing new paths from names of files and from other paths, checking for various properties of paths and creating files and folders at specific paths.
you need to append the path as a string to sys.path
:
PROJECT_DIR = Path(__file__).parents[2]
sys.path.append(
str(PROJECT_DIR / 'apps')
)
PROJECT_DIR
is instance of PosixPath
which has all the goodies like /
and parents
etc. but you need to convert it to a regular string if you want to use is somewhere a string is expected - like sys.path
.
Support for path-like-objects on sys.path
is coming (see this pull request) but not here yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With