Path module snippets
Code snippets for the pathlib.Path stdlib module.
Read files embedded in source code
If you have files like .json or .txt embedded in your app, i.e. for a module that reads from this file where both the .json/.txt file and the .py file that reads them are in the same subdirectory in your Python app, you need to append the .py file's path to the system path. This lets the Python file open the text file using with open("./example.json", "r") as f:.
| Add module path to sys.path | |
|---|---|
Example: read json file
As an example, say you have a package named my_pymodule, with code structured like this:
| my_pymodule package | |
|---|---|
From reader.py, you want to load ./values.json and return to a function that calls the reader.py file, i.e. main.py.
Then in src/my_pymodule/main.py, import the read_values() function. Calling main.py will set your path to wherever you called the script from, but read_values() will always open the example.json file that exists in the same path as the reader.py module:
| src/my_pymodule/main.py | |
|---|---|
Append module's 'grandparent' path
Appends the path ../.. to Python's path. Add more .parent for more deeply nested modules.
This is useful if you have a path like sandbox/ at your root. In the sandbox apps you build in this directory, whatever your entrypoint is (i.e. sandbox/ex_app/main.py), add the code below to fix paths when running sandbox apps from the directory above sandbox/.