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

share|improve this question

17 Answers 17

up vote 1270 down vote accepted

Yes. Use os.path.splitext:

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
share|improve this answer
9  
the use of basename is a little confusing here since os.path.basename("/path/to/somefile.ext") would return "somefile.ext" – Jiaaro Sep 19 '11 at 21:35
8  
wouldn't endswith() not be more portable and pythonic? – Sebastian Mach Aug 28 '13 at 16:42
60  
@klingt.net Well, in that case, .asd is really the extension!! If you think about it, foo.tar.gz is a gzip-compressed file (.gz) which happens to be a tar file (.tar). But it is a gzip file in first place. I wouldn't expect it to return the dual extension at all. – nosklo Jan 16 '14 at 20:18
73  
The standard Python function naming convention is really annoying - almost every time I re-look this up, I mistake it as being splittext. If they would just do anything to signify the break between parts of this name, it'd be much easier to recognize that it's splitExt or split_ext. Surely I can't be the only person who has made this mistake? – ArtOfWarfare Jan 7 '15 at 23:27
7  
@Vingtoft You mentioned nothing about werkzeug's FileStorage in your comment and this question has nothing about that particular scenario. Something might be wrong with how you are passed the filename. os.path.splitext('somefile.ext') => ('somefile', '.ext'). Feel free provide an actual counter example without referencing some third party library. – Gewthen Mar 2 '16 at 2:13

New in version 3.4.

import pathlib

print(pathlib.Path('yourPathGoesHere').suffix)

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!

share|improve this answer
3  
example for getting .tar.gz: ''.join(pathlib.Path('somedir/file.tar.gz').suffixes) – user3780389 Aug 3 '17 at 18:15

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)
'.ext'
share|improve this answer
import os.path
extension = os.path.splitext(filename)[1][1:]

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

share|improve this answer

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:

filepath.rpartition('.')[-1]

example:

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

will give you: 'csv'

share|improve this answer

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

Benefits:

  • 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
share|improve this answer
1  
This results in an exception when the file doesn't have any extension. – thiruvenkadam Apr 1 '16 at 13:42
    
This answer absolutely ignore a variant if a filename contains many points in name. Example get_extension('cmocka-1.1.0.tar.xz') => '.1.0.tar.xz' - wrong. – Seti Volkylany Dec 29 '16 at 8:46
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
share|improve this answer
# 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:

    @staticmethod
    def get_link_extension(link: str)->str:
        if link is None or link == "":
            return ""
        else:
            paths = os.path.splitext(link)
            ext = paths[1]
            new_link = paths[0]
            if ext != "":
                return LinkChecker.get_link_extension(new_link) + ext
            else:
                return ""
share|improve this answer
name_only=file_name[:filename.index(".")

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

share|improve this answer
1  
first, he needs not the name, but extension. Second, even if he would need name, it would be wrong by files like: file.name.ext – ya_dimon Nov 4 '15 at 18:13

If you know the exact file extension for example file.txt then you can use

print fileName[0:-4]

share|improve this answer
1  
That would produce "file". fileName[-4:] would produce ".txt". – Honest Abe Mar 10 '14 at 16:57
    
sorry didnot get your point, would you explain? – esraa Mar 11 '14 at 22:03
    
They want the extension. You are showing a way to remove it. – Honest Abe Mar 11 '14 at 22:37
    
aha I see I thought they want to extract and remove – esraa Mar 18 '14 at 0:20
5  
What if it was an extension like '.jpeg' or '.py' ? :D – Nuno Aniceto Sep 21 '14 at 23:06
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
share|improve this answer
    
This results in the last char of filename being returned if the filename has no . at all. This is because rfind returns -1 if the string is not found. – mattst Jul 25 '16 at 11:33

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])
share|improve this answer

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 
'.gz'

but should be: .tar.gz

The possible solutions are here

share|improve this answer
28  
No, it should be .gz – Robert Siemer May 18 '13 at 10:24
1  
do it twice to get the 2 extensions ? – maazza Jun 12 '13 at 11:55
1  
@maazza yep. gunzip somefile.tar.gz what's the output filename? – FlipMcF Jun 14 '13 at 0:33
1  
This is why we have the extension 'tgz' which means: tar+gzip ! :D – Nuno Aniceto Sep 21 '14 at 23:07
1  
@peterhil I don't think you want your python script to be aware of the application used to create the filename. It's a bit out of scope of the question. Don't pick on the example, 'filename.csv.gz' is also quite valid. – FlipMcF Oct 15 '14 at 21:10

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

os.path.splitext(filename)[1][1:].strip().lower()
share|improve this answer

One option may be splitting from dot:

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

No error when file doesn't have an extension:

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

But you must be careful:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension
share|improve this answer
2  
This would get upset if you're uploading x.tar.gz – Kirill Gordeenko May 11 '12 at 13:59
14  
Not actually. Extension of a file named "x.tar.gz" is "gz" not "tar.gz". os.path.splitext gives ".os" as extension too. – Murat Çorlu May 11 '12 at 20:21
1  
can we use [1] rather than [-1]. I could not understand [-1] with split – user765443 Aug 21 '13 at 5:44
5  
[-1] to get last item of items that splitted by dot. Example: "my.file.name.js".split('.') => ['my','file','name','js] – Murat Çorlu Aug 21 '13 at 8:27
1  
@BenjaminR ah ok, you are making an optimisation about result list. ['file', 'tar', 'gz'] with 'file.tar.gz'.split('.') vs ['file.tar', 'gz'] with 'file.tar.gz'.rsplit('.', 1). yeah, could be. – Murat Çorlu Aug 28 '17 at 8:44

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() 
share|improve this answer
1  
To aid my understanding, please could you explain what additional behaviour the second index/slice guards against? (i.e. the [1:] in .splittext(filename)[1][1:]) - thank you in advance – Samuel Harmer Oct 11 '11 at 9:47
1  
Figured it out for myself: splittext() (unlike if you split a string using '.') includes the '.' character in the extension. The additional [1:] gets rid of it. – Samuel Harmer Oct 11 '11 at 9:55
import os.path
extension = os.path.splitext(filename)[1]
share|improve this answer
11  
+1: I use this when I don't want the basename – nosklo Feb 12 '09 at 14:24
10  
Out of curiosity, why import os.path instead of from os import path? – kiswa Aug 26 '11 at 12:40
1  
Oh, I was just wondering if there was a specific reason behind it (other than convention). I'm still learning Python and wanted to learn more! – kiswa Aug 26 '11 at 19:30
35  
it depends really, if you use from os import path then the name path is taken up in your local scope, also others looking at the code may not immediately know that path is the path from the os module. Where as if you use import os.path it keeps it within the os namespace and wherever you make the call people know it's path() from the os module immediately. – dennmat Nov 24 '11 at 18:45
9  
I know it's not semantically any different, but I personally find the construction _, extension = os.path.splitext(filename) to be much nicer-looking. – Tim Gilbert Aug 14 '14 at 3:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.