Open In App

Python Program to Get the File Name From the File Path

Last Updated : 02 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will be looking at the program to get the file name from the given file path in the Python programming language. Sometimes during automation, we might need the file name extracted from the file path. 

Better to have knowledge of:

Method 1: Python OS-module

Example1: Get the filename from the path without extension split() 

Python’s split() function breaks the given text into a list of strings using the defined separator and returns a list of strings that have been divided by the provided separator.

Python3




import os
path = 'D:\home\Riot Games\VALORANT\live\VALORANT.exe'
print(os.path.basename(path).split('/')[-1])


Output:

VALORANT.exe

Example 2: Get the File Name From the File Path using os.path.basename

The base name in the given path can be obtained using the built-in Python function os.path.basename(). The function path.basename() accepts a path argument and returns the base name of the pathname path.

Python3




import os
 
file_path = 'C:/Users/test.txt'  # file path
 
# using basename function from os
# module to print file name
file_name = os.path.basename(file_path)
 
print(file_name)


Output:

test.txt

Example 3: Get the File Name From the File Path using os.splitext

This method will end up with a file and it’s an extension but what if we need only the file name without an extension or only extensions. Here splitext function in the os module comes into the picture. This method will return a tuple of strings containing filename and text and we can access them with the help of indexing.

Example:

Python3




import os
 
file_path = 'C:/Users/test.txt'
 
file_name = os.path.basename(file_path)
file = os.path.splitext(file_name)
 
print(file# returns tuple of string
 
print(file[0] + file[1])


Output:

('test', '.txt')
test.txt

Method 2: Get the File Name From the File Path Using Pathlib

The Python Pathlib package offers a number of classes that describe file system paths with semantics suitable for many operating systems. The standard utility modules for Python include this module. Although stem is one of the utility attributes that enables extracts of the filename from the link without extension if we want an extension with the file we can use name attributes

Example:

Python3




from pathlib import Path
 
file_path = 'C:/Users/test.txt'
 
# stem attribute extracts the file
# name
print(Path(file_path).stem)
 
# name attribute returns full name
# of the file
print(Path(file_path).name)


Output:

test
test.txt

Method 3: Get the File Name From the File Path Using Regular expressions

We can use a regular expression to match the file name with the specific pattern.

Pattern - [\w]+?(?=\.)

This pattern is divided into 3 patterns

  • [\w] matches the words inside the set
  • +? matches the string if it’s present only once before ? keyword
  • (?=) matches all characters without newline and make sure to stop at.

Example:

Python3




import re
 
file_path = 'C:/Users/test.txt'
pattern = '[\w-]+?(?=\.)'
 
# searching the pattern
a = re.search(pattern, file_path)
 
# printing the match
print(a.group())


Output:

test

Method 4: Use the built-in Python function split() to split the file path into a list of individual components, and then use the rsplit() method:

you can use the built-in Python function split() to split the file path into a list of individual components, and then use the rsplit() method to split the last component (which should be the file name and extension) into a list containing the file name and extension. You can then use indexing to extract the file name from this list.

Here is an example of how this can be done:

Python3




def get_file_name(file_path):
    file_path_components = file_path.split('/')
    file_name_and_extension = file_path_components[-1].rsplit('.', 1)
    return file_name_and_extension[0]
 
# Example usage
file_path = 'C:/Users/test.txt'
result = get_file_name(file_path)
print(result)  # Output: 'test'


Output: test

This approach first uses the split() function to split the file path into a list of individual components, separated by the ‘/’ character. The rsplit() method is then used to split the last component (which should be the file name and extension) into a list containing the file name and extension, using the ‘.’ character as the separator. The file name is then extracted from this list using indexing. This approach will work for any file path and extension, as long as the file path is in a format that can be parsed using the split() and rsplit() methods.



Previous Article
Next Article

Similar Reads

Python | Print the initials of a name with last name in full
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space excep
3 min read
Python IMDbPY – Getting Person name from searched name
In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be name. Syntax : names[0]['name']Here names is the lis
2 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
Python program to Get Month Name from Month Number
Given a datetime object or month number, the task is to write a Python program to get the corresponding month name from it. Examples: Input : test_date = datetime(2020, 4, 8)Output : AprilExplanation : 4th Month is April. Input : test_date = datetime(2020, 1, 8)Output : JanuaryExplanation : 1st Month is January. Method #1 : Using strftime() + %B In
4 min read
Python Program to Get the Class Name of an Instance
In this article, we will see How To Get a Class Name of a class instance. For getting the class name of an instance, we have the following 4 methods that are listed below: Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.Use the type() function and __name__ to get the type or class of the Object/In
4 min read
MoviePy – Getting Original File Name of Video File Clip
In this article we will see how we can get the original file name of the video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Original file name is the name of the original video that existed in the first place i.e which was loaded, even after altering and editing of the vi
2 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to know certain hacks of functions. This article disc
3 min read
Python IMDbPY – Get each episode name of each season of the series
In this article we will see how we can get the name/title of each episode for each season of the series from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes by adding episodes info set to the series In order to get this
3 min read
Python IMDbPY – Get series name from the episode
In this article we will see how we can get the series name from the episode from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes details by adding episodes info set to the series. In order to get this we have to do the f
2 min read