Algorithm
-
Define a function:
- Name:
extract_extension
- Parameters:
file_name
(string)
- Name:
-
Find the last occurrence of '.' in the file name:
- Use the
rfind
method on the file name.
- Use the
-
Check if a dot is found and it is not the first character:
- If the last dot index is not -1 (dot found) and it is less than
len(file_name) - 1
.
- If the last dot index is not -1 (dot found) and it is less than
-
Extract the extension using string slicing:
- If conditions from step 3 are met, use string slicing to get the substring from
last_dot_index + 1
to the end.
- If conditions from step 3 are met, use string slicing to get the substring from
-
Return the extracted extension:
- Return the extracted extension if it exists, otherwise return "No extension".
-
Example usage:
- Define a sample file name.
- Call the
extract_extension
function with the sample file name. - Print the result.
Code Examples
#1 Code Example- Python Programing Using splitext() method from os module
Code -
Python Programming
import os
file_details = os.path.splitext('/path/file.ext')
print(file_details)
print(file_details[1])
Copy The Code &
Try With Live Editor
Output
('/path/file', '.ext')
.ext
.ext
#2 Code Example- Python Programing Using pathlib module
Code -
Python Programming
import pathlib
print(pathlib.Path('/path/file.ext').suffix)
Copy The Code &
Try With Live Editor
Output
.ext
Demonstration
Python Programing Example to Extract Extension From the File Name-DevsEnv