Saturday, November 16, 2024
Google search engine
HomeLanguagesPython Program to Get the File Name From the File Path

Python Program to Get the File Name From the File Path

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.

RELATED ARTICLES

Most Popular

Recent Comments