Python | os.path.splitext() method
Last Updated :
22 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is submodule of OS module in Python used for common pathname manipulation.
os.path.splitext()
method in Python is used to split the path name into a pair root and ext. Here, ext stands for extension and has the extension portion of the specified path while root is everything except ext part.
ext is empty if specified path does not have any extension. If the specified path has leading period (‘.’), it will be ignored.
For example consider the following path names:
path name root ext
/home/User/Desktop/file.txt /home/User/Desktop/file .txt
/home/User/Desktop /home/User/Desktop {empty}
file.py file .py
.txt .txt {empty}
Syntax: os.path.splitext(path)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a str or bytes object representing a path.
Return Type: This method returns a tuple that represents root and ext part of the specified path name.
Code: Use of os.path.splitext() method
import os
path = '/home/User/Desktop/file.txt'
root_ext = os.path.splitext(path)
print ( "root part of '% s':" % path, root_ext[ 0 ])
print ( "ext part of '% s':" % path, root_ext[ 1 ], "\n" )
path = '/home/User/Desktop/'
root_ext = os.path.splitext(path)
print ( "root part of '% s':" % path, root_ext[ 0 ])
print ( "ext part of '% s':" % path, root_ext[ 1 ])
|
Output:
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/':
Reference: https://docs.python.org/3/library/os.path.html
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...