Extract File Name from Path for Any OS/Path Format

Extract File Name From Path For Any OSPath Format

In Python, we can easily extract the file name from an entire file path using built-in functions and libraries. You might be wondering why you need to extract file names from the absolute path of a file in Python. The answer is that different computer systems use different separators for various file systems. During automation, which is prevalent nowadays, it is essential to separate file names hassle-free.

Extracting File Name from File Paths for Platform-Independent Solutions

We need name extraction from file paths to obtain platform-independent solutions to the above problem. There are many ways to do this, such as:

Let’s look at how we can implement all of the above methods one by one.

In Python, you can extract the file name from a file path using different methods, such as the rsplit() method, the basename() function from the OS module, and the Path module. These methods are platform-independent and can be used to handle different file systems and separators across various computer systems during automation. Each method has its syntax, and you can choose one based on your requirements.

Method 1: Using rsplit() Method

The rsplit() method is similar to the split() method, but it separates words or characters starting from the right instead of the left. It returns a list of words or characters in a string separated by a delimiter. The syntax of the function is:

our_string.rsplit(separator,maxsplit)

The separator is the delimiter which can be any character if specified. The default value for this parameter is space.

The maxsplit parameter defines the number of splits that should be done. It is an optional argument. It’s default value is assigned to -1, which splits all individual items. Let’s take a look at the code for the same. You don’t need to install anything additional to use this function.

#code for extracting file name

#taking input for file path
file_name=input("Enter the absolute path of your file=")
#spliting the entire file path
filename_compo=file_name.split('/')
#using rsplit() to separate file name
file_name_extracted = filename_compo[-1].rsplit('.', 1)
#displaying only the file name
print("The file name is=",file_name_extracted[0])

The output would be:

Enter the absolute path of your file=C:/Downloads/askpython_files.txt
The file name is= askpython_files
Using Rsplit Method
Using rsplit() Method

Suggested: What is __file__ variable in Python?

Method 2: Using basename() Function from the OS Module

The operating system (OS) module in Python contains miscellaneous functions that can establish connections between the operating system and the user. We will use the basename() function from this module which can extract the base name of the file. No need to install or download any extra libraries to use this function as it comes under Python’s default utility modules. It’s syntax is:

os.path.basename(path_of_the_file)

The code used for extracting the file name is:

#code for extracting file name

#importing required modules
import os
#taking input for file path
file_abpath=input("Enter the absolute path of your file=")
#using the basename function from the os module
file_nameextracted = os.path.basename(file_abpath)
#returns the tuple containing the file
file_final = os.path.splitext(file_nameextracted)
#only the first index
print("The filename is=", file_final[0])

The output of the above code is:

Enter the absolute path of your file=C:/users/shreya/downloads/myfolder.txt
The filename is= myfolder

Method 3: Using the Path Module in Python

This is another method that can be used to obtain the file name from the absolute path of a file in a computer. The Path module in Python allows us to represent class instances with semantics appropriate for different operating systems, making it a versatile solution for working with file paths.

In the following way we can use the path module to extract the file name from the path in python.

#code for extracting file name

#importing required modules
from pathlib import Path
 
file_path = input("enter absolute file path=")
# the name attribute returns full name of the file
print("The name of the file is=", Path(file_path).name)

The output would be:

enter absolute file path=C:/downloads/myfolder/firstprogram.py
The name of the file is= firstprogram.py

Do check out: Convert PDF to TXT file using Python.

Conclusion:

In this tutorial, we’ve explored various methods to extract file names from absolute file paths in Python. With multiple libraries available, you can choose the method that best suits your needs. As you continue to work with files, how might you integrate these techniques into your projects for seamless file handling and automation?