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

Python文件追加报错:AttributeError问题解析与解决

解决歌单生成器中的AttributeError问题

嘿,作为Python新手遇到这种文件操作的坑太正常了,我来帮你拆解这个问题!

错误含义解释

你看到的AttributeError: 'str' object has no attribute 'append'意思是:你试图给一个字符串调用append()方法,但append()是Python列表专属的方法,字符串根本没有这个功能。

具体看你出错的代码行:

"playlist" + str(log) + ".txt".append(songs[choice1])

这里"playlist" + str(log) + ".txt"是一个拼接出来的字符串(比如playlist0.txt),你想让它“追加”歌曲内容,但字符串没法这么做——你要操作的是这个字符串对应的文件,不是字符串本身!

解决方案

要实现把歌曲写入歌单文件,你需要正确打开文件并写入内容,而不是给文件名字符串调用append。同时我也帮你修正代码里的其他小问题:

修正后的完整代码

cont = "0"
log = 0

# 用with语句打开文件,自动关闭,更安全
with open("songs.txt", "r") as data:
    songs = data.readlines()
    # 排序时去掉每行末尾的换行符,避免排序后换行混乱
    songs = [song.strip() for song in songs]
    songs.sort()

while log < 20:
    cont = input("Do you want to make a playlist? [Yes or No]").lower()
    while cont == "yes":
        # 优化歌曲列表的打印方式,不用手动写1到20
        for idx, song in enumerate(songs[:20], start=1):
            print(f"{idx}. {song}")
        
        # 先确定文件名,此时log还没递增,文件名正确
        new_playlist = f"playlist{log}.txt"
        print(f"Creating playlist: {new_playlist}")
        
        choice = int(input("Please enter the first choice of song you would like in your playlist [Type the allocated number please]"))
        # 检查输入的数字是否在有效范围内
        if 1 <= choice <= len(songs[:20]):
            choice1 = choice - 1
            # 用with打开文件,用追加模式("a"),如果文件不存在会自动创建
            with open(new_playlist, "a", encoding="utf-8") as playlist_file:
                # 写入歌曲时加上换行符,保证每行一首
                playlist_file.write(f"{songs[choice1]}\n")
            print(f"Added {songs[choice1]} to {new_playlist}!")
        else:
            print("Invalid choice, please enter a number between 1 and 20!")
        
        # 询问是否继续给当前歌单加歌曲
        cont = input("Do you want to add another song to this playlist? [Yes or No]").lower()
    
    # 完成一个歌单后,log递增,准备下一个歌单
    log += 1

关键修改点说明

  • 文件操作的正确姿势:用with open(文件名, 模式)语句来打开文件,它会自动帮你关闭文件,避免资源泄漏。写入时用"a"(追加模式),这样每次添加歌曲都会加到文件末尾,不会覆盖之前的内容;如果文件不存在,Python会自动创建它。
  • 修复文件名和log的顺序:原来的代码先递增log再处理文件名,会导致文件名和实际创建的文件序号不一致(比如第一次创建的是playlist1.txt而不是playlist0.txt),现在先处理文件名再递增log。
  • 优化歌曲打印:用enumerate循环打印歌曲列表,不用手动写1到20的编号,更简洁且不易出错。
  • 输入合法性检查:添加了对用户输入数字的范围检查,避免用户输入超出歌曲列表长度的数字导致索引错误。
  • 处理换行符:读取歌曲时去掉每行末尾的换行符,写入时再加上,保证文件里的格式整齐。

这样修改后,你的歌单生成器就能正常工作,支持创建多个歌单并添加歌曲啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:56:47