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

Python文件修改问题:如何替换文件第三行指定位置的歌曲名?

修复Python函数替换文件第三行后内容被完全覆盖的问题

问题描述

我需要编写函数my_mp4_playlist(file_path, new_song),实现两个功能:打开文件并将第三行的歌曲名替换为new_song,然后打印新的文件内容。

初始文件内容

Tudo Bom;Static and Ben El Tavori;5:13;
I Gotta Feeling;The Black Eyed Peas;4:05;
Instrumental;Unknown;4:15;
Paradise;Coldplay;4:23;
Where is the love?;The Black Eyed Peas;4:13;

预期输出

Tudo Bom;Static and Ben El Tavori;5:13;
I Gotta Feeling;The Black Eyed Peas;4:05;
new_song;Unknown;4:15;
Paradise;Coldplay;4:23;
Where is the love?;The Black Eyed Peas;4:13;

现有代码

def my_mp4_playlist(file_path, new_song):
    with open(file_path, "r") as reading_file:
        data = reading_file.read()
        data = data.split("\n")
        individual = []
        for element in data:
            individual.append(element.split(";"))
        for song in individual:
            song.remove(song[3]) #this removes a space leftover as the last value in each list
        individual = individual[3][0].replace(individual[3][0], new_song)
    with open(file_path, "w") as writing_file:
        writing_file.write(individual)
    with open(file_path, "r") as complete_file:
        print(complete_file.read())

遇到的问题

使用replace()方法后,整个文件内容被覆盖,仅保留new_song,请问该如何解决?


解决方案

你的核心问题出在这行代码:individual = individual[3][0].replace(individual[3][0], new_song)——你直接把原本存储所有行数据的列表,替换成了单独的new_song字符串,所以写入文件时自然只剩下这一个值。我们需要保留其他行的内容,只针对性修改第三行的歌曲名。

下面是修正后的代码:

def my_mp4_playlist(file_path, new_song):
    # 1. 读取文件所有行,保留每行的格式(包括末尾换行符)
    with open(file_path, "r") as reading_file:
        lines = reading_file.readlines()
    
    # 2. 确保文件至少有3行,避免索引越界
    if len(lines) >= 3:
        # 拆分第三行的元素(先去掉末尾换行符,再按分号拆分)
        song_parts = lines[2].strip().split(";")
        # 替换第一个元素(歌曲名)为new_song
        song_parts[0] = new_song
        # 重新拼接成符合原格式的行(加回分号和换行符)
        lines[2] = ";".join(song_parts) + ";\n"
    
    # 3. 将修改后的所有行写入文件,保留其他行内容
    with open(file_path, "w") as writing_file:
        writing_file.writelines(lines)
    
    # 4. 读取并打印更新后的文件内容
    with open(file_path, "r") as complete_file:
        print(complete_file.read())

代码细节说明

  • 读取文件:用readlines()直接获取所有行的列表,每一行自带换行符,方便后续还原原格式。
  • 修改第三行:
    • 先判断文件行数是否足够,避免出现索引越界的报错。
    • 用strip()去掉第三行末尾的换行符,再用split(";")拆分成分号分隔的元素列表,精准定位到歌曲名字段。
    • 替换完成后用";".join(song_parts)重新拼接,再加回原格式的分号和换行符,保证和其他行格式一致。
  • 写入文件:用writelines()把整个行列表写入,这样其他未修改的行会被完整保留,只更新第三行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:42:38