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
copy
splitext(p)
copy
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.
The input path can consist of longer paths not just the the filename.