How to Get the Basename of a File in Python?

In this article, I will help you to how to get the basename of a file in Python. As a Python developer, working on a project I often needed to extract the filename from a full file path while dealing with file management tasks. Let us get into the details with some practical examples.

Get the Basename of a File in Python

The basename of a file is the final component of a file path. For instance, in the path /Users/johndoe/Documents/report.pdf , the basename is report.pdf. Extracting this basename can be crucial for file processing tasks, such as logging, reporting, or simply displaying file names to users.

Read How to Create a CSV File in Python?

1. Use os.path.basename() Method

Let’s look at how to use os.path.basename() with some practical examples. First, you need to import the os module in Python. Then you can use the basename() method to extract the filename from a given path.

import os

file_path = "/Users/johndoe/Documents/report.pdf"
basename = os.path.basename(file_path)
print(basename) 

Output:

report.pdf

You can see the output in the screenshot below.

Get the Basename of a File in Python

In this example, os.path.basename() extracts report.pdf from the full path.

Handle Different Path Formats

One of the strengths of os.path.basename() is its ability to handle different path formats, including those used in various operating systems.

Example with a Windows Path

import os

file_path = "C:\\Users\\johndoe\\Documents\\report.pdf"
basename = os.path.basename(file_path)
print(basename)

Output:

report.pdf

You can see the output in the screenshot below.

How to Get the Basename of a File in Python

Even though the path format is different, os.path.basename() correctly extracts the basename.

Work with User Input

If your application accepts file paths from user input, you can use os.path.basename() to ensure you always get the correct file name.

import os

file_path = input("Enter the full file path: ")
basename = os.path.basename(file_path)
print(f"The file name is: {basename}")

Output:

Enter the full file path:

You can see the output in the screenshot below.

Get the Basename of a File in Python with User Input

This snippet prompts the user to enter a file path and then prints the basename.

Check out How to Read Large CSV Files in Python?

Advanced Usage

Let us see some advantages usage of os.path.basename().

Extract Basename Without Extension

Sometimes, you might need to get the basename without the file extension. You can achieve this by combining os.path.basename() with os.path.splitext().

import os

file_path = "/Users/johndoe/Documents/report.pdf"
basename = os.path.basename(file_path)
name, ext = os.path.splitext(basename)
print(name)  # Output: report

In this example, os.path.splitext() splits the basename into the name and extension, allowing you to isolate the name.

Loop Through Multiple Files

If you need to process multiple files in a directory, you can use os.path.basename() in a loop.

import os

directory = "/Users/johndoe/Documents"
for filename in os.listdir(directory):
    file_path = os.path.join(directory, filename)
    basename = os.path.basename(file_path)
    print(basename)

This code lists all files in the specified directory and prints their basenames.

Read How to Write Bytes to File in Python?

Application: Log File Names

Let’s implement a practical example where we log the basenames of all processed files.

import os

def log_file_names(directory, log_file):
    with open(log_file, 'w') as log:
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            basename = os.path.basename(file_path)
            log.write(f"{basename}\n")
    print(f"File names logged to {log_file}")

# Usage
directory = "/Users/johndoe/Documents"
log_file = "/Users/johndoe/Documents/processed_files.log"
log_file_names(directory, log_file)

In this script, we define a function log_file_names that writes the basenames of all files in a directory to a log file.

Check out How to Create a Python File in Terminal?

Conclusion

In this article, I explained how to get the basename of a file in Python. I discussed the complete usage of os.path.basename() method by handling different path formats, taking examples with Windows paths, and taking user input. I also discussed advanced usage to extract basename without extension, loop through multiple names, and a real-time application.

You may also 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.