Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting extension from filename in Python

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

like image 753
Alex Avatar asked Feb 12 '09 14:02

Alex


People also ask

How do I get the filename extension in Python?

We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.

What is the extension of a Python file?

py extension contain the Python source code. The Python language has become very famous language now a days. It can be used for system scripting, web and software development and mathematics.


1 Answers

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', '') 
like image 153
nosklo Avatar answered Sep 30 '22 17:09

nosklo