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()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python String isprintable()
Python frozenset()
Python String isnumeric()
Python Program to Check If Two Strings are Anagram
Python List insert()
Python Program Read a File Line by Line Into a List
APIs in Node.js vs Python - A Comparison
Python Sets
Python timestamp to datetime and vice-versa
Python String expandtabs()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Set add()
Python Statement, Indentation and Comments
Python Program to Slice Lists
Python Keywords and Identifiers
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String translate()
Python Object Oriented Programming
Python Dictionary fromkeys()
Python reversed()
Python String islower()
Python Program to Solve Quadratic Equation
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Recursion
Python String rpartition()
Python classmethod()
Python Program to Get File Creation and Modification Date
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Append to a File