python file directory path code example

Example 1: get directory of file python

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

Example 2: find the path to a file python

import os
print os.path.abspath("something.exe")

Example 3: pathlib path get directory of current file

import pathlib
pathlib.Path(__file__).parent.absolute()

Example 4: python file from path

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

Example 5: python file location path

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)

Example 6: python file directory

from os import path
dir_path = path.dirname(__file__)