import os
class SplitFilePath():
@classmethod
def dirname(cls, path):
try:
return os.path.dirname(path)
except Exception as e:
return None
@classmethod
def basename(cls, path):
try:
return os.path.basename(path)
except Exception as e:
return None
@classmethod
def basename_without_ext(cls, path):
try:
file_full_name = os.path.basename(path)
return os.path.splitext(file_full_name)[0]
except Exception as e:
return None
@classmethod
def ext(cls, path):
try:
file_full_name = os.path.basename(path)
return os.path.splitext(file_full_name)[1][1:]
except Exception as e:
return None
if __name__ == '__main__':
text_file = r'F:\text\gold.txt'
# 提取父目录
print(SplitFilePath.dirname(text_file))
# F:\text
# 提取完整文件名
print(SplitFilePath.basename(text_file))
# gold.txt
# 提取文件名
print(SplitFilePath.basename_without_ext(text_file))
# gold
# 提取扩展名
print(SplitFilePath.ext(text_file))
# txt
Python获取文件路径的父级目录、文件名、扩展名
于 2023-06-27 10:42:11 首次发布