How to Use the Python os.path.splitext() Method

Contents
In this article, you will learn how to use the Python os.path.splitext() method.
Python os.path.splitext() Method
The os.path.splitext() method in Python is used to split a file path into a tuple containing the file’s root and extension.
Syntax:
The syntax for using os.path.splitext() is as follows:
import os
root, ext = os.path.splitext(file_path)
Parameters:
file_path
: The path of the file you want to split.root
: The root of the file.ext
: The extension of the file.
Example:
Here’s an example of how to use os.path.splitext() to split a file path:
import os
file_path = '/home/user/documents/myfile.txt'
root, ext = os.path.splitext(file_path)
print("Root:", root)
print("Extension:", ext)
In this example, file_path is the path of the file we want to split. We then call the os.path.splitext() method on the file path and assign the resulting values to the variables root and ext. Finally, we print the values of root and ext.
If the file path does not have an extension, the os.path.splitext() method will return an empty string for the extension. For example, if we call os.path.splitext() on a file path that does not have an extension like this:
import os
file_path = '/home/user/documents/myfile'
root, ext = os.path.splitext(file_path)
print("Root:", root)
print("Extension:", ext)
The output will be:
Root: /home/user/documents/myfile
Extension:
In this case, the ext variable is an empty string because there is no extension in the file path.