python add path

How to Permanently Add Directory to Python Path

Every time you run a python command or import python package, the python interpreter looks into a certain pre-defined set of directories and sub directories for python binary as well as the packages used in the command. This list of directories is known as Python PATH environment variable. It is available for all python commands run in a terminal, or python script. If the package or function mentioned in your command is not present in any of the directories listed in python path variable, then you will get a ‘command not found’ error. To fix this issue, it is advisable to add directory containing your package to python path. In this article, we will learn how to permanently add directory to python path.

How to Permanently Add Directory to Python Path

Generally, all environment variables are loaded at the beginning of session. They are generally stored in .bashrc file in user’s home directory.

Open this file in editor.

$ vi ~/.bashrc

Add the following line to it. Replace /new/path below with the directory that you want to add to python path.

export PYTHONPATH="${PYTHONPATH}:/new/path"

The above command basically appends new directory to existing value of PYTHONPATH environment variable which stores all the locations where python looks for commands and scripts during execution. Save and close the file.

Run the following command to apply changes.

$ source ~/.bashrc

Alternatively, you can close terminal and start a new session. From now on, every time you start a new session the new directory will also be a part of python path, meaning python will look into this folder to search for binaries and scripts required for execution.

If you don’t want to permanently add directory to python path but only for present session, then run the following command directly from terminal.

$ export PYTHONPATH="${PYTHONPATH}:/new/path"

In this article, we have learnt how to add directory to python path. By default, when you install a package using pip or easy_install it will be installed in one of the directories mentioned in Python path environment variable. But if you have installed it at another location, then you need to follow the above steps to add directory to python path.

Also read:

How to Install Python Package with .whl file
How to Convert JSON to Pandas Dataframe
How to Write List to File in Python
How to Fix Invalid Use of Group Function
How to Insert Current Datetime in PostgreSQL

Leave a Reply

Your email address will not be published. Required fields are marked *