How to add path for Python on Mac?

I thought that by doing the following in Python:

import sys
sys.path.append("/home/me/mydir")

I could append a directory to my Python path. If I print sys.path, my directory appears in the list.

However, when I open a new terminal session, the directory is no longer in sys.path, and Python can’t import modules saved in that directory.

What am I doing wrong? I read that .profile or .bash_profile could help. Should I add the following to my .bash_profile or .zshrc file to make it work?

PATH="/Me/Documents/mydir:$PYTHONPATH"
export PATH

You should modify your shell configuration file (.bash_profile, .bashrc, or .zshrc if you’re using Zsh). Instead of modifying PATH, modify PYTHONPATH directly. Here’s what you should do:

Open the .bash_profile or .zshrc file using a text editor:

nano ~/.bash_profile # or ~/.zshrc for Zsh users

Add the following line to append your directory to PYTHONPATH:

export PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"

Save the file and exit the editor. Then, reload the shell configuration:

source ~/.bash_profile # or source ~/.zshrc

This will ensure that the directory is included in the Python path whenever you start a new terminal session.

You can modify the Python sys.path dynamically by adding your directory to sys.path at the start of your script:

import sys
sys.path.append("/Me/Documents/mydir")

This solution works well if you’re running a specific script and want to ensure that Python knows about the module location every time.

You can also use Python’s site module to modify sys.path more persistently. The site module allows you to include directories that Python will always consider when searching for modules.

First, create a .pth file in the Python site-packages directory.

For example:

echo "/Me/Documents/mydir" >> $(python3 -m site --user-site)/mydir.pth

This method ensures that your directory is always added to sys.path when Python is run, without needing to modify sys.path manually in each script.

By using any of these methods, you’ll successfully add Python to path mac so that Python can locate the modules in your custom directory every time you run your code.