
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get File Name from File Path in Python
In this article, we will learn a python program to get the file name from the file Path.
Methods Used
The following are the various methods to accomplish this task ?
Using the OS module functions
Using Pathlib Module
Using Regular expressions(regex module)
Method 1: Using the OS Module Functions
Get the File Name From the File Path using the split() Function
The split() function splits a string into a list. We can define the separator; the default separator is any whitespace.
Algorithm (Steps)
Following are the Algorithms/steps to be followed to perform the desired task. ?
Use the import keyword to import the os module.
Create a variable to store the input file path.
Use the split() function to split the file path into a list of words based on the '/' separator.
Get the last element from the list using negative indexing(indexing from the end i.e -1, -2?.).
print the resultant filename.
Example
The following program returns the filename from the given file path using the split() function ?
# importing os module import os # input file path inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' # Printing the given file path print("The given file path is:",inputFilepath) # splitting the file path into a list of words based on '/' and # getting the last element using negative indexing print("The File Name is:\n",os.path.basename(inputFilepath).split('/')[-1])
Output
On execution, the above program will generate the following output ?
The given file path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf The File Name is: tutorialsPoint.pdf
Get the File Name From the File Path using the os.path.basename
Using the built-in Python function os.path.basename(), one may determine the base name in the specified path. The base name of the pathname path is returned by the function path.basename(), which takes a path argument.
Example
The following program returns the filename from the given file path using os.path.basename() function ?
# importing os module import os # input path of the file inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' # Printing the given input path print("Give Input Path is:",inputFilepath) # getting the last component(main file name )of the input file path print("The File Name is:\n",os.path.basename(inputFilepath))
Output
On execution, the above program will generate the following output ?
Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf The File Name is: tutorialsPoint.pdf
Get the File Name From the File Path using the os.splitext()
If we only need the file name without an extension or only extensions, this method will produce a file and its extension. Here, the os module's splitext function comes into play.
The os.splitext() method will return a tuple of strings that includes the filename and the content, which we can access using indexing.
Example
The following program returns the filename from the given file path using os.splitext() function ?
# importing os module import os inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' # Printing the given input path print("Give Input Path is:",inputFilepath) # getting the file name from the file path fileName = os.path.basename(inputFilepath) # splitting the file using the splittext() function full_file = os.path.splitext(fileName) # printing the tuple of a string containing file name and extension separately print(full_file) # Concatenating file name with file extension using string concatenation print("The File Name is:\n",full_file[0] + full_file[1])
Output
Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf ('tutorialsPoint', '.pdf') The File Name is: tutorialsPoint.pdf
Method 2: Using Pathlib Module
Several classes that describe file system paths with semantics appropriate for numerous operating systems are available in the Python Pathlib module. This module is one of the fundamental Python utility modules.
If we want an extension with the file, we can utilize name attributes, even if the stem is one of the utility attributes that enables extracts of the filename from the link without extension.
Example
The following program returns the filename from the given file path using Path() function and stem attribute of Pathlib Module ?
# importing Path from pathlib module from pathlib import Path # input file path inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' # getting the filename from the file path # here the stem attribute extracts the file name from filepath print('File Name is:',Path(inputFilepath).stem) # here the name attribute returns full name(along with extension) # of the input file print("The File Name Along with Extension is:",Path(inputFilepath).name)
Output
File Name is: tutorialsPoint The File Name Along with the Extension is: tutorialsPoint.pdf
Method 3: Using Regular expressions(regex module)
In order to match the file name with the particular pattern, we can use a regular expression.
pattern - [\w]+?(?=\.)
The above pattern is divided into 3 patterns ?
[\w] ? matches the words inside the set
+? ? matches the string if appears just once before the ? keyword
(?=) ? matches any character without a newline and Keep in mind that to stop at.
regex re.search() method
The Python regex re.search() method searches the entire target string for occurrences of the regex pattern and returns the appropriate Match Object instance where the match was found. Only the first match to the pattern in the target string is returned by re.search().
Example
The following program returns the filename from the given file path using the Regular expressions (regex) ?
# importing re(regex) module import re # input file path inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' # regex pattern to extract the file name regex_pattern = '[\w-]+?(?=\.)' # searching/matching the pattern of the input file path result = re.search(regex_pattern, inputFilepath) # printing the match name print("The File Name is:",result.group())
Output
The File Name is: tutorialsPoint
Conclusion
In this article, we learned how to use the three different methods to get the file name from the given file path. We learned how to modify the provided file path using the built-in features of the OS module to meet our needs.