附加到文件错误 - PYTHON

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了附加到文件错误 - PYTHON相关的知识,希望对你有一定的参考价值。

请耐心等待我,因为我是python的新手,正在通过创建简单的程序来学习。最近我开始创建自己的程序来生成一个文件,并允许用户选择并将它们存储在每个文件中。在这个例子中,我正在寻找一个歌曲播放列表生成器。虽然我很难直到我遇到这个错误,但我无法修复。这是一个文件的打开。

这是守则

cont = "0"
log = 0
data = open("songs.txt", "r")
songs = data.readlines()
songs.sort()


while log < 20:
    cont = input("Do you want to make a playlist? [Yes or No]")
    while cont == "yes":
        print ("1. ", songs[0],"2. ", songs[1],"3. ", songs[2],"4. ", songs[3],"5. ", songs[4],"6. ", songs[5],"7. ", songs[6],"8. ", songs[7],"9. ", songs[8],"10. ", songs[9],"11. ", songs[10],"12. ", songs[11],"13. ", songs[12],"14. ", songs[13],"15. ", songs[14],"16. ", songs[15],"17. ", songs[16],"18. ", songs[17],"19. ", songs[18],"20. ", songs[19])
        new = "playlist" + str(log) + ".txt"
        print(new)
        log = log + 1
        cont = "no"
        choice = int(input("Please enter the first choice of song you would like in your playlist [Type the allocated number please]"))
        choice1 = choice - 1
        "playlist" + str(log) + ".txt".append(songs[choice1])

但是,我的代码应该允许用户从我的打印功能中选择歌曲,然后将它们添加到生成的播放列表中,然后对他们想要的播放列表重复此操作。现在我的代码给了我一个错误信息。

File "playlists.py", line 18, in <module>
"playlist" + str(log) + ".txt".append(songs[choice1])
AttributeError: 'str' object has no attribute 'append'

这个错误说明是什么,我怎么能克服它。

在此先感谢和期待!

答案

问题是这一行:

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

只是超级错误/有点像伪代码。要附加到文本文件,需要打开它以进行追加,然后写入它。这样做:

with open("playlist" + str(log) + ".txt", "a") as myfile:
    myfile.write(str(songs[choice1]))

以上是关于附加到文件错误 - PYTHON的主要内容,如果未能解决你的问题,请参考以下文章

如何重新附加片段(片段未附加到活动 Kotlin)

附加到文件错误 - PYTHON

java 简单的代码片段,展示如何将javaagent附加到运行JVM进程

Python - 将字典列表附加到嵌套的默认字典时出现关键错误

片段 MyFragment 未附加到 Activity

如果它不存在,如何创建一个 CSV 文件,然后只附加到它 Python