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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github