Extracting extension from filename in Python

Alex Source

Is there a function to extract the extension from a filename?



answered 9 years ago nosklo #1

Yes. Use os.path.splitext:

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
>>> file_extension

answered 9 years ago Brian Neal #2

import os.path
extension = os.path.splitext(filename)[1]

answered 7 years ago wonzbak #3

import os.path
extension = os.path.splitext(filename)[1][1:]

To get only the text of the extension, without the dot.

answered 7 years ago yamex5 #4

Any of the solutions above work, but on linux I have found that there is a newline at the end of the extension string which will prevent matches from succeeding. Add the strip() method to the end. For example:

import os.path
extension = os.path.splitext(filename)[1][1:].strip() 

answered 6 years ago Murat Çorlu #5

One option may be splitting from dot:

>>> filename = "example.jpeg"
>>> filename.split(".")[-1]

No error when file doesn't have an extension:

>>> "filename".split(".")[-1]

But you must be careful:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension

answered 5 years ago blented #6

worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.


answered 5 years ago XavierCLL #7

With splitext there are problems with files with double extension (e.g. file.tar.gz, file.tar.bz2, etc..)

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension 

but should be: .tar.gz

The possible solutions are here

answered 4 years ago Arnaldo P. Figueira Figueira #8

Another solution with right split:

# to get extension only

s = 'test.ext'

if '.' in s: ext = s.rsplit('.', 1)[1]

# or, to get file name and extension

def split_filepath(s):
    get filename and extension from filepath 
    filepath -> (filename, extension)
    if not '.' in s: return (s, '')
    r = s.rsplit('.', 1)
    return (r[0], r[1])

answered 4 years ago staytime #9

extension = filename[filename.rfind('.'):]

answered 4 years ago wookie #10


That will give you the file name up to the first ".", which would be the most common.

answered 3 years ago DragonX #11

# try this, it works for anything, any length of extension
# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs

import os.path

class LinkChecker:

    def get_link_extension(link: str)->str:
        if link is None or link == "":
            return ""
            paths = os.path.splitext(link)
            ext = paths[1]
            new_link = paths[0]
            if ext != "":
                return LinkChecker.get_link_extension(new_link) + ext
                return ""

answered 3 years ago user5535053 #12

def NewFileName(fichier):
    cpt = 0
    fic , *ext =  fichier.split('.')
    ext = '.'.join(ext)
    while os.path.isfile(fichier):
        cpt += 1
        fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
    return fichier

answered 3 years ago PascalVKooten #13

Surprised this wasn't mentioned yet:

import os
fn = '/some/path/a.tar.gz'

basename = os.path.basename(fn)  # os independent
Out[] a.tar.gz

base = basename.split('.')[0]
Out[] a

ext = '.'.join(basename.split('.')[1:])   # <-- main part

# if you want a leading '.', and if no result `None`:
ext = '.' + ext if ext else None
Out[] .tar.gz


  • Works as expected for anything I can think of
  • No modules
  • No regex
  • Cross-platform
  • Easily extendible (e.g. no leading dots for extension, only last part of extension)

As function:

def get_extension(filename):
    basename = os.path.basename(filename)  # os independent
    ext = '.'.join(basename.split('.')[1:])
    return '.' + ext if ext else None

answered 2 years ago JeromeJ #14

New in version 3.4.

import pathlib


I'm surprised no one has mentioned pathlib yet, pathlib IS awesome!

If you need all the suffixes (eg if you have a .tar.gz), .suffixes will return a list of them!

answered 1 year ago weiyixie #15

Although it is an old topic, but i wonder why there is none mentioning a very simple api of python called rpartition in this case:

to get extension of a given file absolute path, you can simply type:



path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]

will give you: 'csv'

answered 8 months ago Execuday #16

Even this question is already answered I'd add the solution in Regex.

>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)

answered 3 months ago soheshdoshi #17

You can use a split on a filename:

f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

This does not require additional library

answered 2 months ago Kenstars #18

This is a direct string representation techniques : I see a lot of solutions mentioned, but I think most are looking at split. Split however does it at every occurrence of "." . What you would rather be looking for is partition.

string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]

comments powered by Disqus