JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Get file extension in Python

Author:JIYIK Last Updated:2025/05/05 Views:

This tutorial shows how to get the file extension from a file name in Python.


os.pathExtract extension from file using module in Python

The Python module os.pathpre-makes useful utility functions for manipulating operating system file paths, including opening, saving, and updating, as well as getting information from file paths.

We will use this module to get the file extension in Python.

os.pathThere is a function splitext()that splits the root and extension of a given file path. The function returns a tuple containing the root string and the extension string.

Let's provide an docxexample of a file path with a .

/Users/user/Documents/sampledoc.docx

The expected output should be the extension .docx.

Declare two separate variables extensionand rootto capture splitext()the results of .

import os

path = "/Users/user/Documents/sampledoc.docx"
root, extension = os.path.splitext(path)

print("Root:", root)
print("extension:", extension)

Output:

Root: /Users/user/Documents/sampledoc
Extension: .docx

The extension is now successfully returned from the root file path.


pathlibExtract extension from file using module in Python

pathlibIs a Python module that contains classes that represent file paths and implements utility functions and constants for these classes.

pathlib.Path()Accepts a path string as an argument and returns a new Pathobject.

pathlib.PathThe object has attributes suffixthat return file extension information.

import pathlib

path = pathlib.Path("/Users/user/Documents/sampledoc.docx")

print("Parent:", path.parent)
print("Filename:", path.name)
print("Extension:", path.suffix)

In addition to the root directory, we can also get the parent file path and the actual file name for a given file path by simply calling the and Pathproperties within the object .parentname

Output:

Parent: /Users/user/Documents
Filename: sampledoc.docx
Extension: .docx

What if the file extension is .tar.gzor .tar.bz2?

pathlibA property is also provided for handling files with multiple suffixes. PathThe property in the object suffixesis a list containing all the given file suffixes. If we use the example above and print out suffixesthe property.

import pathlib

path = pathlib.Path("/Users/user/Documents/sampledoc.docx")

print("Suffix(es):", path.suffixes)

Output:

Suffix(es): ['.docx']

So even if there is only one suffix, the output will be a list.

Now try .tar.gzan example using the extension. To convert a list to a single string, use join()the function on an empty string and accept suffixesthe attribute as an argument.

import pathlib

path = pathlib.Path("/Users/user/Documents/app_sample.tar.gz")

print("Parent:", path.parent)
print("Filename:", path.name)
print("Extension:", "".join(path.suffixes))

Output:

Parent: /Users/user/Documents
Filename: app_sample.tar.gz
Extension: .tar.gz

The actual extensions are now displayed instead of a list.

In summary, osthese pathlibtwo modules provide convenient ways to get the file extension from the file path in Python.

osThe module has a function splitextfor separating the root and filename from the file extension. pathlibCreate a Pathobject and simply store the extension in suffixthe attribute.

It is better to use if you anticipate having multiple extensions in a file pathlib, as it suffixesprovides easy support for multiple extensions using the attribute.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Read the first line of a file in Python

Publish Date:2025/05/05 Views:192 Category:Python

In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t

Reading binary files in Python

Publish Date:2025/05/05 Views:119 Category:Python

The program or internal processor interprets the binary file. It contains bytes as content. When we read a binary file, an bytes object of type is returned. open() Read a binary file using the function in Python In Python, we have open() th

Writing bytes to a file in Python

Publish Date:2025/05/05 Views:193 Category:Python

In this tutorial, we will look at how to write bytes to a binary file in Python. Binary files contain strings of type bytes. When we read a binary file, an object of type bytes is returned. In Python, bytes are represented by hexadecimal nu

Python get file name without extension from path

Publish Date:2025/05/05 Views:81 Category:Python

This tutorial will demonstrate various ways to get the file name without extension from a file path in Python. Suppose our goal is to get the file name from a list of file paths that are in the form of strings, such as from the path Desktop

Calculate the time difference between two time strings in Python

Publish Date:2025/05/05 Views:182 Category:Python

Sometimes we have to deal with date and time related problems in programming. In Python, date and time are not data types themselves. Despite this, Python provides a large number of functions and libraries to help deal with such problems. O

Optional parameters in Python

Publish Date:2025/05/05 Views:151 Category:Python

In Python, there is something called default arguments. It is also called optional parameters or optional arguments in python. Parameters refer to the inputs of a function. Functions with multiple optional parameters in Python Whenever you

Writing floating point numbers to a file in Python

Publish Date:2025/05/05 Views:91 Category:Python

Python makes writing data to a file a seamless task. The data is written to the file in the form of strings. In this article, you will learn how to write float values ​​to a file in Python. Writing floating point numbers to a file in Py

How to read specific lines from a file in Python

Publish Date:2025/05/05 Views:181 Category:Python

A common way to read files in Python is to read the file completely and then process specific lines. Reading files in Python is fast, for example, it takes about 0.67 seconds to write a 100MiB file. However, if the file size exceeds 100MB,

Calculating the arithmetic mean in Python

Publish Date:2025/05/05 Views:190 Category:Python

The term arithmetic mean is the average of the numbers. The mathematical formula to determine the arithmetic mean is to divide the sum of the numbers by the count. It is determined in Python in the following way. Use mathematical formulas.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial