You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何去除路径前缀 从文件URI中提取仅保留末尾文件名

Python实现从file URI提取文件名方案

通用方案(推荐,适配所有合法file URI)

用标准库urllib解析URI、os.path提取文件名,支持前缀变化、路径含特殊编码字符的场景,鲁棒性更高。
实现代码:

from urllib.parse import unquote, urlparse
import os

# 原始输入字符串
raw_input = "file:///storage/emulated/0/memento/files/329403216/2021-08-31 10.35.47.jpg, file:///storage/emulated/0/memento/files/329403216/2021-08-31 10.36.13.jpg, file:///storage/emulated/0/memento/files/329403216/2021-08-31 10.36.23.jpg"

# 拆分得到所有独立URI,去除首尾空格
uri_list = [item.strip() for item in raw_input.split(',')]
res_list = []

for uri in uri_list:
    # 解析URI拿到路径,解码URL特殊字符
    path = unquote(urlparse(uri).path)
    # 提取路径末尾的文件名
    res_list.append(os.path.basename(path))

# 拼接为最终格式
result = ', '.join(res_list)
print(result)

运行输出和需求的结果完全一致。


简易方案(适合固定前缀场景)

如果确定所有URI的路径格式固定、没有特殊编码字符,可以直接用字符串分割简化实现,代码更短:

raw_input = "file:///storage/emulated/0/memento/files/329403216/2021-08-31 10.35.47.jpg, file:///storage/emulated/0/memento/files/329403216/2021-08-31 10.36.13.jpg, file:///storage/emulated/0/memento/files/329403216/2021-08-31 10.36.23.jpg"

result = ', '.join([item.strip().split('/')[-1] for item in raw_input.split(',')])
print(result)

内容的提问来源于stack exchange,提问作者spyfly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:51:03