The os module in the standard library includes the path sub-module which provides useful functions for working with and manipulating paths.
The splitext()
function in the path
submodule is used to split a pathname into a tuple containing the filename and the file extension. The name of the function is a shortened form for "split extension". An extension in pathnames refers to an additional part that is added onto the end of a file name or directory path to denote a specific file type, or to help identify the contents of the file or directory. The extension part is typically preceded by a period( . ).
For example, Python source files usually have a ".py" extension, which means a file will typically look like, "filename.py".
To use the splitext()
function, we will first need to import it in our program as follows.
from os.path import splitext
splitext(p)
p |
The file name/path. |
The function splits the input path at the last period/dot and returns a tuple in the form of (root, ext) , the extension is everything from the last dot to the end of the string. The extension will be empty if the input path does not contain or ends with a period.
from os.path import splitext
paths = ["john.jpg", "taylor.mp3", "tests.py", "styles.css", "project.js"]
for p in paths:
print(splitext(p))
The input path can consist of longer paths not just the the filename.
from os.path import splitext
paths = ["/project/files/images/john.jpg", "/project/files/music/taylor.mp3", "/project/tests.py", "/project/static/css/styles/index.css", "/project/static/js/index.js"]
for p in paths:
print(splitext(p))