Python| os.path.splitext() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.splitext()
方法用于将路径名拆分为一对root和ext 。在这里, ext代表扩展,具有指定路径的扩展部分,而root是除ext部分之外的所有内容。
如果指定的路径没有任何扩展名,则ext为空。如果指定的路径有前导句点('.'),它将被忽略。
例如,考虑以下路径名:
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.
代码:使用 os.path.splitext() 方法
# Python program to explain os.path.splitext() method
# importing os module
import os
# path
path = '/home/User/Desktop/file.txt'
# Split the path in
# root and ext pair
root_ext = os.path.splitext(path)
# print root and ext
# of the specified path
print("root part of '% s':" % path, root_ext[0])
print("ext part of '% s':" % path, root_ext[1], "\n")
# path
path = '/home/User/Desktop/'
# Split the path in
# root and ext pair
root_ext = os.path.splitext(path)
# print root and ext
# of the specified path
print("root part of '% s':" % path, root_ext[0])
print("ext part of '% s':" % path, root_ext[1])
输出:
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/':
参考: https://docs。 Python.org/3/library/os.path.html