Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。 os.path模塊是Python中OS模塊的子模塊,用於通用路徑名操作。
os.path.splitext()
Python中的方法用於將路徑名分為成對的根和擴展名。在這裏,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}
用法: os.path.splitext(path)
參數:
path:代表文件係統路徑的path-like對象。 path-like對象是表示路徑的str或bytes對象。
返回類型:此方法返回一個表示指定路徑名的根和擴展部分的元組。
代碼: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
相關用法
- Python next()用法及代碼示例
- Python os.dup()用法及代碼示例
- Python set()用法及代碼示例
- Python Decimal max()用法及代碼示例
- Python PIL ImageOps.fit()用法及代碼示例
- Python os.rmdir()用法及代碼示例
- Python sympy.det()用法及代碼示例
- Python Decimal min()用法及代碼示例
- Python os.readlink()用法及代碼示例
- Python os.writev()用法及代碼示例
- Python os.readv()用法及代碼示例
- Python PIL RankFilter()用法及代碼示例
- Python os.rename()用法及代碼示例
- Python os.sendfile()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.path.splitext() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。