How To Get A Full Path Of A Sibling Folder In Python

Pavol Kutaj
1 min readFeb 18, 2022

--

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 ../assets folder

  • RULE: Do not combine paths using string concatenation with the + operator
  • 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 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'))
  1. __file__ returns the absolute path of the script (i.e. you can't do the above from the REPL)
  2. os.path.dirname(__file__) returns the abs path of its parent folder (./src)
  3. os.path.join() concatenates the previous, with step-back control statement, and target folder
  4. os.path.abspath() normalizes the returned path for cross-platform compatibility
  • dots are two control statements
  • . do nothing
  • .. step-back
  • for 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

4. SOURCES

--

--

No responses yet