Skip to main content

File paths

In most apps the code makes use of information from files on the hard drive. In order to access such files, a path must be provided. Python's built-in pathlib module can be used for this purpose.

caution

Never use a static path to access a file (e.g. '/home/users/foo/app/entity/file.txt', '../file.txt', or 'file.txt')! This might work fine when testing on your local machine, but will most likely crash when the app is published and runs on a server (different username, folder structure and operating system).

Assume an application with the following structure of the app directory:

app
├── entity_type_a
│ ├── __init__.py
│ ├── controller.py
│ └── parametrization.py
├── __init__.py
└── file.txt

We can make use of Path(__file__) as a starting point, which points to the file in which the code is invoked. On this path object, we can easily navigate to the parent directory by calling Path(__file__).parent. In the structure above, getting the file file.txt in the controller of entity_type_a can thus be done by:

# entity_type_a/controller.py
from pathlib import Path

entity_folder_path = Path(__file__).parent # entity_type_a
file_path = entity_folder_path.parent / 'file.txt'

with file_path.open() as f:
content = f.read()

This implementation allows your application/project/module to be portable. For example, the folder entity_type_a (and even controller.py!) can be renamed without breaking the link to file.txt, because the navigation is relative to the source file (controller.py).