程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

python如何分离文件名和扩展名

hfteth 2025-03-06 15:25:50 技术文章 17 ℃

作为新手,如果需要用python将文件名和扩展名分开,你会怎么处理?

full_files = [
    'dsie.txt',
    'woeifj.py',
    'jfosdi.cpp',
    'dkjfowe.43.mp3',
    'doif.tar.gz'
]

通常如果上面的文件名,一般都会想到用字符串分割再拼接的方式:

for file in full_files:
    file_split = file.split(".")
    name = '.'.join(file_split[0 : -1])
    suffix = '.' + file_split[-1]
    print(f"name : {name}, suffix : {suffix}")

但上面的方式我不是很推荐,你可以直接用python自带的接口:

import os

for file in full_files:
    pure_path = os.path.splitext(file)
    name = pure_path[0]
    suffix = pure_path[1]
    print(f"name : {name}, suffix : {suffix}")

还有一种方式是我最推荐的,我之前写过《在python中如何去检测文件是否存在?》文章中提到过:

import pathlib

for file in full_files:
    pure_path = pathlib.PurePath(file)
    name = pure_path.stem
    suffix = pure_path.suffix
    print(f"name : {name}, suffix : {suffix}")

上述运行效果如下:

name : dsie, suffix : .txt
name : woeifj, suffix : .py
name : jfosdi, suffix : .cpp
name : dkjfowe.43, suffix : .mp3
name : doif.tar, suffix : .gz

大家有什么想法也可以相互交流相互学习。

最近发表
标签列表