The aim of this playbook🏁 is to outline the step back when navigating relatively with Python with the aim to get a full path of a sibling folder.
E.g. you have a script in
./scr/foo.py and you want the full path of the
- RULE: Do not combine paths using string concatenation with the
- Use only
- 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 concatenation of a file-path
""" for a script in ./src to get the full path of the ../assets folder """
assets_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'assets'))
__file__returns the absolute path of the script (i.e. you can't do the above from the REPL)
os.path.dirname(__file__)returns the abs path of its parent folder (
os.path.join()concatenates the previous, with step-back control statement, and target folder
os.path.abspath()normalizes the returned path for cross-platform compatibility
- dots are two control statements
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)).