python dirname code example

Example 1: 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 2: python get base directory

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

Example 3: os path splitext

import os
basename, ext = os.path.splitext('inputfile.txt')

Example 4: python os get dir path

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

getcwd() # Get the current working directory