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
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
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.
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
Syntax: Path(file_path).stem
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
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. 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.
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