Python joining current directory and parent directory with os.path.join

You can use normpath, realpath or abspath:

import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
print goal_dir  # prints C:/here/I/am/../../my_dir
print os.path.normpath(goal_dir)  # prints C:/here/my_dir
print os.path.realpath(goal_dir)  # prints C:/here/my_dir
print os.path.abspath(goal_dir)  # prints C:/here/my_dir

Lately, I discovered pathlib.

from pathlib import Path
cwd = Path.cwd()
goal_dir = cwd.parent.parent / "my_dir"

Or, using the file of the current script:

cwd = Path(__file__).parent
goal_dir = cwd.parent.parent / "my_dir"

In both cases, the absolute path in simplified form can be found like this:

goal_dir = goal_dir.resolve()

consider to use os.path.abspath this will evaluate the absolute path

or One can use os.path.normpath this will return the normalized path (Normalize path, eliminating double slashes, etc.)

One should pick one of these functions depending on requirements

In the case of abspath In Your example, You don't need to use os.path.join

os.path.abspath("../../my_dir")

os.path.normpath should be used if you are interested in the relative path.

>>> os.path.normpath("../my_dir/../my_dir")
'../my_dir'

Other references for handling with file paths:

  • pathlib - Object-oriented filesystem paths
  • os.path— Common pathname manipulations

Tags:

Python

Os.Path