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

Python 3:如何移除文件路径字符串中的指定部分?

嘿,我来帮你搞定这个音频文件路径的字符串处理问题!首先得明确你想移除路径里的哪部分内容,我给你分几种常见的场景来演示Python 3的实现方法:

原始路径列表

先把你的原始列表整理一下,方便后续操作:

Mix = [
    '/home/pi/Music/The Very Best Of The Stone Roses/02 She Bangs The Drums.mp3',
    '/home/pi/Music/The Smiths/The Sound Of The Smiths/1-20 Sheila Take A Bow.mp3',
    '/home/pi/Music/The Smiths/The Sound Of The Smiths/1-21 Girlfriend In A Coma.mp3',
    "/home/pi/Music/The Smiths/The Sound Of The Smiths/1-22 I Started Something I Couldn't.mp3",
    '/home/pi/Music/The Smiths/The Sound Of The Smiths/1-23 Last Night I Dreamt That Somebo.mp3'
]

场景1:移除固定前缀 /home/pi/Music/

如果你想去掉所有路径开头的公共根目录,有两种简单方式:

方法1:字符串替换(最直接)

prefix_to_remove = '/home/pi/Music/'
cleaned_paths = [path.replace(prefix_to_remove, '') for path in Mix]

处理后的结果会保留艺术家、专辑和歌曲名的层级:

[
    'The Very Best Of The Stone Roses/02 She Bangs The Drums.mp3',
    'The Smiths/The Sound Of The Smiths/1-20 Sheila Take A Bow.mp3',
    ...
]

方法2:用os.path模块(更专业,跨平台友好)

如果你想让代码更适配不同操作系统的路径规则,推荐用os.path.relpath()获取相对路径:

import os

base_directory = '/home/pi/Music/'
cleaned_paths = [os.path.relpath(path, base_directory) for path in Mix]

这个方法会自动处理路径分隔符,结果和上面的字符串替换一致,但鲁棒性更强。

场景2:只保留歌曲文件名(去掉所有目录层级)

如果你只需要每个文件的名字,直接用os.path.basename():

import os

only_filenames = [os.path.basename(path) for path in Mix]

处理后得到:

[
    '02 She Bangs The Drums.mp3',
    '1-20 Sheila Take A Bow.mp3',
    '1-21 Girlfriend In A Coma.mp3',
    "1-22 I Started Something I Couldn't.mp3",
    '1-23 Last Night I Dreamt That Somebo.mp3'
]

场景3:移除文件名开头的编号(比如02 、1-20 )

如果想去掉文件名里的前置编号,用正则表达式来匹配替换最方便:

import re
import os

# 先提取文件名,再移除开头的编号
cleaned_filenames = [
    re.sub(r'^\d+(-\d+)? ', '', os.path.basename(path)) 
    for path in Mix
]

正则表达式^\d+(-\d+)? 会匹配开头的数字(可能带连字符的编号,比如1-20)和后续的空格,替换为空字符串后得到:

[
    'She Bangs The Drums.mp3',
    'Sheila Take A Bow.mp3',
    'Girlfriend In A Coma.mp3',
    "I Started Something I Couldn't.mp3",
    'Last Night I Dreamt That Somebo.mp3'
]

场景4:自定义移除特定内容

如果有特定的字符串需要移除(比如某张专辑名),直接用replace()针对性处理即可:

# 比如移除路径中的"The Sound Of The Smiths/"部分
cleaned_paths = [
    path.replace('/The Smiths/The Sound Of The Smiths/', '/The Smiths/') 
    for path in Mix
]

你可以根据自己的实际需求选择对应的方法,如果还有更具体的移除规则,随时调整就行!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:30:06