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 a knowledge of –
Method 1: Get the File Name From the File Path Using Python OS-module
This method will end up with a file and it’s an extension but what if we need only file name without extension or only extensions. Here splitext function in the os module comes into the picture.
Syntax - os.path.splittext(file_name)
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
Stem attribute enables to extracts the filename from the link without extension but 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. Please refer to this article for learning regex
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.