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