When programming in Python, you sometimes need to access a path off your project root from deep in another directory hierarchy. Here is an effortless way to do it that always works: 

 

 

import sys
print(sys.path[1])

This way, you can use relative paths from the Python file to get to your configuration files, data files, and secrets files. However, please refrain from pushing your secrets to GitHub and other online repositories.

However, there is an even better way that uses pathlib from the Python standard library.

SO what’s so cool about pathlib? Well, it allows you to write code that runs on any operating system without modification (so, at least, Mac, Linux, and even Windows).

It does this by starting everything from your home directory. On Mac, this will be, for example, /Users/andy. On Linux, /home/andy, and Windows c:\users\andy.

From there, all you need to do is use a standard set of subdirectories, and everything will be smooth and seamless.

Here’s how I ensure my data is always in the right place:

import pathlib
appname = "trips"
home_dir = pathlib.Path.home()
data = home_dir / "data" / appnamedata.mkdir(parents=True, exist_ok=True)

Now you can use the data variable to refer to the correct directory, regardless of where your apps run.