def retrieveSong(): # Function that retrieves a random song from the file.
file = open("Songs.csv", "r")
count = 0
for line in file: # Finds out how many lines (and therefore songs) there are.
count += 1
length = count
print(length)
randomIndex = randint(0, length) # Picks a random line.
print(randomIndex)
count = 0
print(count)
for line in file: # Loops through the file until it finds the right line.
if count == randomIndex:
song = line.split(",")
count += 1
for item in song: # Gets rid of the \n at the end of each line.
item = str.strip(item)
file.close()
return song # Returns the song name and artist, in a list where song[0] is the name and song[1] is the artist.
The program is supposed to retrieve a random song from a CSV file. The song is retrieved into a list, split at each comma, so that it will be ['song name', 'artist']
. Most of it works fine - the only parts that don't seem to work are the final two 'paragraphs':
for line in file: # Loops through the file until it finds the right line.
if count == randomIndex:
song = line.split(",")
count += 1
for item in song: # Gets rid of the \n at the end of each line.
item = str.strip(item)
file.close()
return song # Returns the song name and artist, in a list where song[0] is the name and song[1] is the artist.
I keep getting an error telling me that the line that says return song
is trying to return a variable that has never been assigned, which leads me to believe that something is wrong with the following lines.
for line in file: # Iterates through the file until it finds the right line.
if count == randomIndex:
song = line.split(",")
count += 1
I'm fairly certain that, for some reason, the program doesn't ever recognise count == randomIndex
as True, even though it's supposed to. I've added print statements everywhere to (attempt to) work out what parts aren't working as expected, but I have no idea why. I'm not a Python expert, so I don't really know what to do.