Member-only story
Simple trick to work with relative paths in Python
Calculate the file path at runtime with ease
The goal of this article is to calculate a path to a file in a folder in your project. The reason we calculate this path is that you refer to the correct location no matter where the code is installed. This is the case when you share your code with a coworker or deploy your code on a webserver e.g.
You can’t hardcode the (expected) location of the file because C:/users/mike/myproject/config/.env
doesn’t exist on your machine or on the server we’re deploying to. Ideally we’d like to specify the path relative to the root folder of our project.
In this article we’ll check out a simple Python trick that allows us to refer to files relative to our project folder in a very easy way. Let’s code!
TL/DR; Check out ‘The Trick” below!
Use cases
Two quick example on where this trick comes in handy:
- Loading an environment file from e.g.
/config/.env
- We have an API that receives files; the files should always be stored in
data/received_audio_files
for example.
Preparation
In this article we’ll set up our project structure like this: