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.
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.
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.
('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
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.