Algorithm


  1. Define a function:

    • Name: extract_extension
    • Parameters: file_name (string)
  2. Find the last occurrence of '.' in the file name:

    • Use the rfind method on the file name.
  3. 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.
  4. 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.
  5. Return the extracted extension:

    • Return the extracted extension if it exists, otherwise return "No extension".
  6. 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

x
+
cmd
('/path/file', '.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

x
+
cmd
.ext
Advertisements

Demonstration


Python Programing Example to Extract Extension From the File Name-DevsEnv