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:
Python strptime()
Python Dictionary popitem()
Python for Loop
Python Inheritance
Python help()
Python Program to Print Colored Text to the Terminal
Python Program to Check Armstrong Number
Python Program to Create a Countdown Timer
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Sort a Dictionary by Value
Python Program to Find All File with .txt Extension Present Inside a Directory
Python frozenset()
Python datetime
Python hasattr()
Node.js vs Python for Backend Development
Python Program to Create Pyramid Patterns
Python strftime()
Python object()
Python Program to Convert Kilometers to Miles
Intelligent Projects Using Python - Santanu Pattanayak
Introduction to Scientific Programming with Python - Joakim Sundnes
Python @property decorator
Python Program to Find the Size (Resolution) of a Image
Python Program to Count the Number of Digits Present In a Number
Python Errors and Built-in Exceptions
Python exec()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Print Hello world!
Python vars()
Python Dictionary items()
Python Program to Differentiate Between del, remove, and pop on a List