VOOZH about

URL: https://www.geeksforgeeks.org/python/python-os-path-basename-method/

⇱ Python | os.path.basename() method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | os.path.basename() method

Last Updated : 23 Feb, 2026

os.path.basename() method in Python is used to extract the final part of a file path. This final part can be a file name or the last folder name. It is commonly used when working with file paths to get only the name without the full path.


Output
file.txt

Explanation:

  • p = "/home/user/file.txt" stores the full file path.
  • r = os.path.basename(p) extracts the last part of the path.

Syntax

os.path.basename(path)

  • Parameter: path - A file path from which the base name is extracted.
  • Return Value: Returns a string containing the file name or last folder name.

Examples

Example 1: This example extracts the file name from a relative path. This is useful when working with local project files.


Output
data.csv

Explanation:

  • p = "data.csv" stores relative file path.
  • r = os.path.basename(p) extracts file name.

Example 2: This example extracts the last folder name from a directory path.


Output
Documents

Explanation:

  • p = "/home/user/Documents" stores folder path.
  • r = os.path.basename(p) extracts folder name.

Example 3: This example shows what happens when the path ends with a trailing slash. It helps understand how basename() behaves with folder paths ending in /.


Output

Explanation:

  • p = "/home/user/Documents/" stores a folder path that ends with a slash.
  • r = os.path.basename(p) returns empty string because the last part after / is empty.
Comment