How to Get File Name Without Extension in Python?

In this tutorial, I will explain how to get file name without extension in Python. As a Python programmer, we get various situations to work with files and it is important to know how to get a file name without extension. I will explain four important methods to achieve this task with examples.

Get File Name Without Extension in Python

Let us learn how to get file name without extension in Python.

Read How to Write Multiple Lines to a File in Python?

Method 1: Use os.path.splitext

The os.path module in Python provides a method called splitext that splits the file path into a tuple (root, ext), where root is the path without the extension, and ext is the file extension.

Example:

import os

file_path = "/Users/john_doe/Documents/report.pdf"
file_name, file_extension = os.path.splitext(file_path)
print(file_name) 

Output:

/Users/john_doe/Documents/report

You can refer to the screenshot below to see the output.

Get File Name Without Extension in Python

In this example, os.path.splitext splits the path into /Users/john_doe/Documents/report and .pdf. We then print the file_name to get the path without the extension.

Check out How to Write Lines to a File in Python?

Method 2: Use pathlib.Path.stem

The pathlib module, introduced in Python 3.4, provides an object-oriented approach to handle file paths. The Path class has a stem attribute that returns the file name without the extension.

Example:

from pathlib import Path

file_path = Path("/Users/jane_doe/Pictures/vacation.jpg")
file_name = file_path.stem
print(file_name) 

Output:

vacation

You can refer to the screenshot below to see the output.

How to Get File Name Without Extension in Python

Here, Path.stem directly gives us the file name without the extension, making the code cleaner and more readable.

Read How to Clear a File in Python?

Method 3: Use str.rsplit

If you prefer a more manual approach, you can use the Python rsplit method of strings to split the file name and remove the extension.

Example:

file_path = "/Users/alex_smith/Downloads/music.mp3"
file_name = file_path.rsplit('.', 1)[0]
print(file_name) 

In this example, rsplit splits the string from the right at the first occurrence of the dot, effectively removing the extension.

Output:

/Users/alex_smith/Downloads/music

You can refer to the screenshot below to see the output.

Get File Name Without Extension in Python str.rsplit

Check out How to Read XML Files in Python?

Method 4: Use Regular Expressions

For more complex scenarios, regular expressions can be a powerful tool. The re module in Python allows you to use regular expressions to find and manipulate strings.

Example:

import re

file_path = "/Users/emily_clark/Work/presentation.pptx"
file_name = re.sub(r'\.[^.]+$', '', file_path)
print(file_name)  # Output: /Users/emily_clark/Work/presentation

In this example, the regular expression r'\.[^.]+$' matches the file extension, and re.sub replaces it with an empty string, effectively removing the extension.

Read How to Skip the First Line in a File in Python?

Handle Edge Cases

When working with file paths, it’s essential to handle edge cases to ensure your code is robust. Here are a few scenarios to consider:

  1. Files Without Extensions: Ensure your code can handle files that don’t have an extension.
  2. Hidden Files: On Unix-based systems, files starting with a dot are hidden (e.g., .bashrc). Ensure your code correctly handles these files.
  3. Multiple Dots: Files can have multiple dots in their names (e.g., archive.tar.gz). Decide whether you want to remove only the last extension or all extensions.

Example:

from pathlib import Path

def get_file_name_without_extension(file_path):
    path = Path(file_path)
    if path.suffix:
        return path.stem
    return path.name

# Test cases
print(get_file_name_without_extension("/Users/john_doe/.bashrc"))  # Output: .bashrc
print(get_file_name_without_extension("/Users/jane_doe/archive.tar.gz"))  # Output: archive.tar
print(get_file_name_without_extension("/Users/alex_smith/README"))  # Output: README

In this example, we use Path.suffix to check if the file has an extension. If it does, we return Path.stem; otherwise, we return the file name as is.

Check out How to Split a File into Multiple Files in Python?

Conclusion

In this article, I helped you to learn how to get file name without extension in Python. I explained four methods to achieve this task such as using the os.path.splitext, using pathlib.Path.stem, using str.rsplit, and using regular expressions. I discussed how to handle edge cases.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.