1

Need help with my code, trying to create a music game. I am getting a 'AttributeError: 'list' object has no attribute 'split'. Help would be appreciated.

Thanks

import random

read = open("Songs.txt", "r")
songs = read.readlines()
songlist = []
#readlines - https://stackoverflow.com/questions/38105507/when-should-i-ever-use-file-read-or-file-readlines
for i in range(len(songs)):
 songlist.append(songs[i].strip('\n'))

songname = random.choice(songlist)
#https://pynative.com/python-random-choice/ - random choice
songs = songs.split()
letters = [word[0] for word in songs]
firstguess = input("Please enter your first guess for the name of the song.")
if firstguess is True:
    print("Well done, you have been awarded 3 points.")
    
elif firstguess is False:
    print("Unlucky, that answer is incorrect. Please try again to win 1 point.")

secondguess = input("Please enter your second guess for the name of the song. Last try, make sure to think before typing!")
if secondguess is True:
    print("Well done, you managed to clutch 1 point.")
elif secondguess is False:
    print("Unlucky, maybe you will know the next song.")
        

1 Answers1

3

Please refer also to this question: Attribute Error: 'list' object has no attribute split

From this you can see that split is an attribute of strings not lists! The solution from the above question was to split each string/line of the list, so use something like:

songs = [sentence.split() for sentence in songs]

To be clear here, sentence is an arbitrary iterator and can be named more appropriately (e.g. like verse) for your purpose. Even though it does not matter to the code execution, good naming is always helpful.

Fnguyen
  • 1,159
  • 10
  • 23
  • That's great, solved my issue! Thanks for your help! – Duncan MacDonald Sep 17 '19 at 09:39
  • No problem, as a new contributor I also like to point out that answers can be marked as solved if you want to indicate a solved problem. You should only do this if you really need no other solutions/alternatives. – Fnguyen Sep 17 '19 at 09:40