Pythonの実際の戦闘ケース-ファイルパス、ファイル名、拡張子をフルパスから分離します

問題

完全な
パスパス= 'C:\ ProgramData \ Dell \ InventoryCollector \ Log \ ICDebugLog.txt'に従って、ファイルパス、ファイル名、および拡張子をパスから分離します。

回答

>>> path = 'C:\\ProgramData\\Dell\\InventoryCollector\\Log\\ICDebugLog.txt'
>>> print(path)
C:\ProgramData\Dell\InventoryCollector\Log\ICDebugLog.txt

# 定义 path 路径
path = 'C:\\ProgramData\\Dell\\InventoryCollector\\Log\\ICDebugLog.txt'
# 获取文件路径
>>> ls1 = path.split('\\')
>>> ls1
['C:', 'ProgramData', 'Dell', 'InventoryCollector', 'Log', 'ICDebugLog.txt']
>>> ls2 = ls1[0:len(ls1)-1:]
>>> ls2
['C:', 'ProgramData', 'Dell', 'InventoryCollector', 'Log']
>>> new_path = '\\'.join(ls2)
>>> print(new_path)
C:\ProgramData\Dell\InventoryCollector\Log

#获取文件名
>>> ls1[len(ls1)-1]
'ICDebugLog.txt'

#获取文件名后缀
>>> tt = ls1[len(ls1) -1]
>>> tt
'ICDebugLog.txt'
>>> tt.split('.')
['ICDebugLog', 'txt']
>>> ls = tt.split('.')
>>> ls[1]
'txt'

おすすめ

転載: blog.csdn.net/XY0918ZWQ/article/details/111198023