I have been trying to use create a list of an artist's top 10 songs on Spotify (using Spotipy) and then save these songs to a txt file in a list but I am at a dead end with how to do it. Sorry if it's super obvious!
Also I would love to then be able to put these songs into a playlist. I have worked out how to create a playlist, but not how to add specific songs to it, so any advice would be welcome!
My code is:
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyOAuth
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="",
client_secret="",
redirect_uri="http://localhost:8080/"))
# shows tracks from a specific artist
choice = input("What artist's songs do you want some names of? ")
with open('songs.txt', 'r') as song_file:
contents = song_file.read()
results = sp.search(q=[choice], limit=10)
for idx, track in enumerate(results['tracks']['items']):
print(idx, track['name'])
with open('songs.txt', 'w+') as song_file:
song_file.write(contents)
for song in contents:
song_file.append(float(row['song']))
I didn't test it but if you want to append new values to file then you don't have to read it and write it again. You may open it in append mode
- open(..., "a")
and then write()
will add text at the end of file.
And when you get data from server then you should run for
-loop inside with open()
and write
new information as text with \n
to put in separated lines
results = sp.search(q=[choice], limit=10)
with open('songs.txt', 'a') as song_file: # open in `append mode`
for idx, track in enumerate(results['tracks']['items']): # run loop inside `with open`
#print(idx, track['name'])
song_file.write( f'{idx} {track['name']}\n' ) # write as string and add `\n` to put in separated lines