dirname python code example

Example 1: python get current file location

import os
os.path.dirname(os.path.abspath(__file__))

Example 2: directory name python

# Directory name from path of file
import os
file_name = "/home/ubuntu/Project/demo.txt"
dir_name = os.path.dirname(file_name)
print(dir_name)

Example 3: python get base directory

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

Example 4: python os get dir path

from os import getcwd # only import "getcwd" from os

getcwd() # Get the current working directory