附加到文件错误 - PYTHON

时间:2018-01-02 07:41:36

标签: python file append

请耐心等待我,因为我是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'

这个错误说明是什么,以及我如何克服它。

提前感谢和期待!

1 个答案:

答案 0 :(得分:0)

问题是这一行:

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

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

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