How to get file extension correctly?

Python 3.4

You can now use Path from pathlib. It has many features, one of them is suffix:

>>> from pathlib import Path
>>> Path('my/library/setup.py').suffix
'.py'
>>> Path('my/library.tar.gz').suffix
'.gz'
>>> Path('my/library').suffix
''

If you want to get more than one suffix, use suffixes:

>>> from pathlib import Path
>>> Path('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> Path('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> Path('my/library').suffixes
[]

Here is a in build module in os. More about os.path.splitext.

In [1]: from os.path import splitext
In [2]: file_name,extension = splitext('/home/lancaster/Downloads/a.ppt')
In [3]: extension
Out[1]: '.ppt'

If you have to fine the extension of .tar.gz,.tar.bz2 you have to write a function like this

from os.path import splitext
def splitext_(path):
    for ext in ['.tar.gz', '.tar.bz2']:
        if path.endswith(ext):
            return path[:-len(ext)], path[-len(ext):]
    return splitext(path)

Result

In [4]: file_name,ext = splitext_('/home/lancaster/Downloads/a.tar.gz')
In [5]: ext
Out[2]: '.tar.gz'

Edit

Generally you can use this function

from os.path import splitext
def splitext_(path):
    if len(path.split('.')) > 2:
        return path.split('.')[0],'.'.join(path.split('.')[-2:])
    return splitext(path)

It will work for all extensions.

Working on all files.

In [6]: inputs = ['a.tar.gz', 'b.tar.lzma', 'a.tar.lz', 'a.tar.lzo', 'a.tar.xz','a.png']
In [7]: for file_ in inputs:                                                                    
    file_name,extension = splitext_(file_)
    print extension
   ....:     
tar.gz
tar.lzma
tar.lz
tar.lzo
tar.xz
.png

Tags:

Python