import spotipy sp = spotipy.Spotify() from pprint import pprint import spotipy.util as util # Get the lineup list artist_list_file = r'artists.txt' with open(artist_list_file) as f: artist_list = f.read().splitlines() # Eyeball the artist list print(len(artist_list)) print(artist_list[0:10]) # Run the list through Spotify's artist search API - keep the top result each time spotify_artist_list = [] for artist_name in artist_list: artist_results = sp.search(q=artist_name, limit=1, type='artist') if len(artist_results['artists']['items']) > 0: spotify_artist_list.append(artist_results['artists']['items'][0]) else: print('Couldn\'t find {0}'.format(artist_name)) # Eyeball the spotify results [(artist['name'], artist['popularity']) for artist in spotify_artist_list][0:10] # Optionally, sort the list by decreasing popularity spotify_artist_list = sorted(spotify_artist_list, key=lambda artist: artist['popularity'], reverse=True) # For each artist, get the top 3 tracks and put them in spotify_track_list spotify_track_list = [] for artist in spotify_artist_list: track_results = sp.artist_top_tracks(artist['uri']) for track in track_results['tracks'][0:3]: spotify_track_list.append(track) # As before, eyeball the tracks we've pulled down [(t['id'], t['name'], t['popularity']) for t in spotify_track_list][0:10] # Set up the user connection so we can create playlists (you would need to put your own details in here for username->return_uri) scope = 'playlist-modify-public' username = 'xxx' client_id = 'xxx' secret_key = 'xxx' return_uri = 'xxx' # Get the token - You need to click a link and paste an address back in token = util.prompt_for_user_token(username, scope, client_id, secret_key , return_uri) # Reconnect with the auth token sp = spotipy.Spotify(auth=token) sp.trace = False # Create the new playlist and get it's ID new_playlist = sp.user_playlist_create(username, 'Glastonbury 3 Track Sampler') playlist_id = new_playlist['id'] print(playlist_id) # the 'user_playlist_add_tracks' function takes a list of track_ids - so make that with some list comprehension track_ids = [t['id'] for t in spotify_tracks] len(track_ids) # the 'user_playlist_add_tracks' only allows adding 100 tracks at a time - hence we loop in 100 item chunks: chunksize = 100 for chunk in [track_ids[i:i + chunksize] for i in range(0, len(track_ids), chunksize)]: results = sp.user_playlist_add_tracks(username, playlist_id, chunk)