Write a Python Program to Get the File Name From the File Path

In Python, getting the file name from a file path can be easily accomplished with the use of built-in functions.

In this tutorial, we will discuss the process of extracting the file name from a file path using Python.


To begin, let us first understand what a file path is.

A file path is a string that represents the location of a file on a computer system.

The file path consists of a directory path and a file name.

The directory path is a series of folders that lead to the file location, while the file name is the name of the file itself.

To extract the file name from a file path, we need to use the os.path module.

This module provides a set of functions that allows us to work with file paths in a platform-independent way.

Here’s a Python program that demonstrates how to get the file name from a file path:

import os

file_path = '/path/to/file/filename.txt'

# Get the file name from the file path
file_name = os.path.basename(file_path)

# Print the file name
print(file_name)

In the code above, we first import the os module.

Next, we define the file_path variable, which represents the file path we want to extract the file name from.

We then use the os.path.basename() function to extract the file name from the file path.

This function returns the last component of the file path, which is the file name.

Finally, we print the file name using the print() function.

That’s it! We have successfully extracted the file name from the file path using Python.


In conclusion, extracting the file name from a file path in Python is a simple task that can be accomplished using the os.path.basename() function.

This function is part of the os.path module, which provides a set of functions for working with file paths in a platform-independent way.