python get parent directory of current file code example

Example 1: python import file from parent directory

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

import mymodule

OR 

import os, sys

sys.path.insert(1, os.getcwd()) 
import variables

Example 2: python get parent directory

import os.path
os.path.dirname('C:\Program Files')

Example 3: python get parent directory

from pathlib import Path
Path('C:\Program Files').parent

Example 4: how do i get parent directory python

from pathlib import Path
path = Path(Path.cwd())
print(path.parent)

Example 5: How do I get the parent directory in Python?

from pathlib import Path
Path(Path.cwd()).parent

Example 6: import file from parent directory python

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# import ../db.py
import db