mardi 28 novembre 2017

How to limit the amount of times it adds to an array / csv file - text based spotify

I've been making a text-based spotify program in python. One of my friends has this as a task in school and he interested me! One of the tasks is to generate random playlists. The one i'm stuck on is generating a random playlist by genre.

5a. Generate a random playlist by genre with at least 5 songs from that genre.

I have a csv file that holds about 20 songs, it has the following information: Song name | Artist | Genre | Track length

This is my current code so far:

import random
import csv

genre_list = ["Pop","Rock","Rap"]
playlist = []

random_genre = random.choice(genre_list)

data = list(csv.reader(open("song.csv")))
name = input("Enter name for the playlist: ")

for row in range(len(data)):
    if random_genre == data[row][2]:
        playlist.append(data[row])

print(playlist)
newfile = open(name + ".csv","w")
for i in range(len(playlist)):
    newfile.write(str(playlist[i][0]+","+playlist[i][1]+","+playlist[i]
[2]+","+playlist[i][3]))
    newfile.write(str("\n"))
newfile.close()
print("done! ")

Only problem I have is that it adds every song from that genre. How do I make it so it limits to 5 songs?

Thanks in advance :)




Aucun commentaire:

Enregistrer un commentaire