Python os.path.dirname() Method

Python os.path.dirname() method is used to get the directory name from the specified path. 

The dirname() method essentially strips off the last component of the path, which is usually a file name or a last directory name, returning the path of the parent directory.

If the provided path is the root directory, this method returns the root directory itself.

If the path doesn’t contain a directory component (i.e., no slashes in the path), it returns an empty string, indicating the current directory.

Syntax

os.path.dirname(path)

Parameters

Name Description
path (string, required) It is a path-like object representing a file system path.

Return Value

It returns a string value representing the directory name from the specified path.

Example 1: Basic usage

Visual Representation of Python os.path.dirname() Method

Here is a file (new.txt) whose directory (env) we will extract:

Screenshot of a directory

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/new.txt'

directory = os.path.dirname(path)

print(directory)

Output

/Users/krunallathiya/Desktop/Code/pythonenv/env

Example 2: Directory Name of a Directory Path

Directory Name of a Directory Path

The “env” directory’s parent directory is “pythonenv” directory. 

Here is the screenshot of a “pythonenv” directory:

Extracting directory name from a directory

import os

dir_path = '/Users/krunallathiya/Desktop/Code/pythonenv/env'

directory = os.path.dirname(dir_path)

print(directory)

Output

/Users/krunallathiya/Desktop/Code/pythonenv

Example 3: Relative path

import os

file_path = 'docs/data.txt'

dir_name = os.path.dirname(file_path)

print(dir_name)

Output

docs

Example 4: No directory component

Figure of No directory component

import os

file_path = 'data.txt'

dir_name = os.path.dirname(file_path)

print(dir_name)

Output

 

You can see that the above output is an empty string because the directory does not exist, just a filename.

See also

Python os.path.abspath()

Python os.path.exists()

Python os.path.join()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.