请耐心等待,因为我是 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]))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句