Table of Contents
In this example, you will learn to extract extension from the file name.
To understand this example, you should have the knowledge of the following Python programming topics:
1. 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].
2. 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.
Related posts:
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Convert Kilometers to Miles
Python memoryview()
Python exec()
Python Program to Find LCM
Python Numbers, Type Conversion and Mathematics
Debug a JavaMail Program
Python Program to Measure the Elapsed Time in Python
Python Anonymous / Lambda Function
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python id()
Python Program to Return Multiple Values From a Function
Python Function Arguments
Python Program to Create a Countdown Timer
Python zip()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Check Whether a String is Palindrome or Not
Python String rfind()
Python Exception Handling Using try, except and finally statement
Python Set discard()
Python String strip()
Python Program to Check if a Number is Positive, Negative or 0
Python @property decorator
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python while Loop
Python Program to Generate a Random Number
Python List pop()
Python Program to Check the File Size
Python Program to Copy a File
Python File I/O Operation
Python all()
Python Set add()