zl程序教程

您现在的位置是:首页 >  Python

当前栏目

【python初级】 os.path.splitext(path)将路径的文件名{只是名称}和后缀名分开

2023-03-20 14:54:07 时间

【python初级】 os.path.splitext将路径的文件名{只是名称}和后缀名分开

1、背景

文件地址是字符串类型,很多人喜欢使用split去分割字符串,关于字符串的split()方法:
split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。

但要注意路径中含有多个点号的情况,如下:

./data_expand/192.168.1.70_01_20210901163745710_250_150_4...jpg

比较推荐的使用python内置的函数去分割:
os.path.splitext(path):将路径的文件名和后缀名分割。其中文件名只是名称。

2、os.path.splitext(path)

os.path.splitext(path):将路径的文件名和后缀名分割。其中文件名只是名称。
path指一个文件的路径(相对路径或者绝对路径)作为参数:
1.1 如果给出的是一个目录和文件名,则输出路径的文件名称和后缀;
1.2 如果给出的是一个目录名,则输出路径和空后缀;

import os
file_path = "D:/test/data_expand/192.168.1.70_01_20210901163745710_250_150_4...jpg"
filename,extension = os.path.splitext(file_path)
print("filename:",filename)   # D:/test/data_expand/192.168.1.70_01_20210901163745710_250_150_4..
print("extension:",extension) # .jpg

file_path ="D:/test/data_expand/"
filename,extension = os.path.splitext(file_path)
print("filename:",filename)         # D:/test/data_expand/
print("extension:",extension)       # 空文件后缀