Is there a function to extract the extension from a filename?
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'
A true one-liner, if you like regex. And it doesn't matter even if you have additional "." in the middle
import re
file_ext = re.search(r"\.([^.]+)$", filename).group(1)
See here for the result: Click Here
import os.path
extension = os.path.splitext(filename)[1][1:]
To get only the text of the extension, without the dot.
You can find some great stuff in pathlib module (available in python 3.x).
import pathlib
x = pathlib.PurePosixPath("C:\\Path\\To\\File\\myfile.txt").suffix
print(x)
# Output
'.txt'
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
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!