Advertisement
Advertisement


Extracting extension from filename in Python


Question

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

2016/09/16
1
1348
9/16/2016 7:11:48 PM

Accepted Answer

Yes. Use os.path.splitext(see Python 2.X documentation or Python 3.X documentation):

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

Unlike most manual string-splitting attempts, os.path.splitext will correctly treat /a/b.c/d as having no extension instead of having extension .c/d, and it will treat .bashrc as having no extension instead of having extension .bashrc:

>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')
2018/09/15
2056
9/15/2018 8:00:05 PM

import os.path
extension = os.path.splitext(filename)[1]
2009/02/12

New in version 3.4.

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'

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!

2020/03/13

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

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

2017/10/10

For simple use cases 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

Also will not work with hidden files in Unix systems:

>>> ".bashrc".split(".")[-1]
'bashrc'    # But this is not an extension

For general use, prefer os.path.splitext

2020/06/16

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()
2012/12/28

Source: https://stackoverflow.com/questions/541390
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]