Python Program to Extract Extension From the File Name

To understand this example, you should have the knowledge of the following Python programming topics:


Example 1: Using splitext() method from os module

import os
file_details = os.path.splitext('/path/file.ext')
print(file_details)
print(file_details[1])

Output

('/path/file', '.ext')
.ext

os.path.splitext() gives a tuple with one item as the name of the file along with the path and the other is the extension of the file. If you want the file extension only, you can print it as shown above file_details[1].


Example 2: Using pathlib module

import pathlib
print(pathlib.Path('/path/file.ext').suffix)

Output

.ext

Using suffix attribute from pathlib module, we can get the extension of a file. In the above example, .ext is the extension of file file.ext.

Note: It works for python 3.4 and above.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges