![]() |
VOOZH | about |
os.path.splitext() method is used to split the pathname into a pair (root, ext), where root is the part of the path before the file extension and ext is the file extension itself. It is particularly useful when you need to extract the file extension or handle files dynamically based on their type. os.pathmodule is submodule of OS module in Python used for common pathname manipulation.
For example consider the following path names:
Path Name | Root | Extension |
|---|---|---|
/home/User/Desktop/file.txt | /home/User/Desktop/file | .txt |
/home/User/Desktop | /home/User/Desktop | (empty) |
file.py | file | .py |
.txt | (empty) | .txt |
Example:
Let's see a basic example of how os.path.splitext() works:
Root: example_file Extension: .txt
Explanation:
os.path.splitext(path)
The method returns a tuple with two elements:
root part of '/home/User/Desktop/file.txt': /home/User/Desktop/file ext part of '/home/User/Desktop/file.txt': .txt root part of '/home/User/Desktop/': /home/User/Desktop/ ext part of '/home/User/Desktop/':
Explanation:
If the file doesn't have an extension, the function will return an empty string for the extension.
Root: example_file Extension:
Explanation: Since "example_file" doesn't have an extension, ext will be an empty string.