How Do I Get the Filename without the Extension from a Path in Python?

Better Stack Team
Updated on June 19, 2024

You can get the filename without the extension from a path in Python using the os.path module. Here's how you can do it:

 
import os

# File path
file_path = '/path/to/file.txt'

# Get the filename without the extension
filename_without_extension = os.path.splitext(os.path.basename(file_path))[0]

print(filename_without_extension)  # Output: file

In this code:

  • os.path.basename(file_path) returns the last component of the path, which is the filename ('file.txt' in this example).
  • os.path.splitext() splits the filename into its base name and extension. It returns a tuple where the first element is the base name and the second element is the extension ('.txt' in this example).
  • [0] at the end of the expression accesses the first element of the tuple, which is the base name without the extension ('file' in this example).
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.