How to step one folder back/higher in Python
The aim of this playbook🏁 is to outline the step back when navigating relatively with Python.
1 min readMay 19, 2021
1. steps for step-back
""" from a script in ./helpers reaching for files in ../assets """
assets_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'assets'))
__file__
returns the absolute path of the scriptos.path.dirname(__file__)
returns the abs path of its parent folder (project root)os.path.join()
concatenates the previous, with a step-back control statement, and target folderos.path.abspath()
normalizes
2. on os.path.join()
- there are two control statements
.
do nothing..
step-back- Do not combine paths using string concatenation
+
- Use only
os.path.join()
- Why? Different computers represent paths in different ways.
- E.g. Windows uses
\
as a separator, while Unix (Mac and Linux) uses/
- in other words, when you see
os.path.join()
it means someone is concatenating a file-path
3. on os.path.abspath(path)
os.path.abspath(path)
---
Return a normalized absolutized version of the pathname path.
On most platforms, this is equivalent to calling the function normpath() as follows:
normpath(join(os.getcwd(), path)).
— from https://docs.python.org/3/library/os.path.html#os.path.abspath