Skip to content

Instantly share code, notes, and snippets.

@ttomasz
Last active May 18, 2024 20:45
Show Gist options
  • Save ttomasz/5135fca7d8b196165961741e4907bccf to your computer and use it in GitHub Desktop.
Save ttomasz/5135fca7d8b196165961741e4907bccf to your computer and use it in GitHub Desktop.
Read text file with song names and create a Spotify playlist out of them
import time
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from tqdm import tqdm
import secrets
#
# pip install spotipy tqdm
# or use requirements.txt
# -------------------------------------
def chunks(lst, n):
"""Function to split the song_ids list into chunks of size n"""
for i in range(0, len(lst), n):
yield lst[i:i + n]
# read song names from text file
with open('./songs.txt', 'r', encoding='utf-8') as f:
songs = [x.strip() for x in f.readlines()]
# connect to spotify
# register app to get tokens first at: https://developer.spotify.com/dashboard/
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=secrets.client_id,
client_secret=secrets.client_secret,
redirect_uri=secrets.redirect_uri,
scope="playlist-read-private playlist-modify-private")) # change to appropriate scope if playlist is public
# more about scopes: https://developer.spotify.com/documentation/general/guides/scopes/
# create a playlist for current user with provided name
playlist_name = 'python-test-playlist'
user_id = sp.me()['id']
sp.user_playlist_create(user_id, playlist_name, public=False)
# find playlist's ID
# there may be multiple playlists with the given name, collect them to a list of tuples (name, id)
playlists = [(x['name'], x['id']) for x in sp.current_user_playlists()['items'] if x['name'] == playlist_name]
# loop over song names and search for them on spotify
song_ids = []
print('Searching for songs...')
for song in tqdm(songs):
results = sp.search(q=song, limit=1, type='track')
# we'll assume first result is correct and save its id
first_result_song_id = results['tracks']['items'][0]['id']
song_ids.append(first_result_song_id)
# add found songs to playlist
print('Adding songs to playlist...')
playlist_id = playlists[0][1] # get the first playlist matching the name
for chunk in chunks(song_ids, 10):
time.sleep(1)
print(f"Adding songs to playlist: {chunk}")
sp.playlist_add_items(playlist_id, chunk)
certifi==2020.6.20
chardet==3.0.4
idna==2.10
requests==2.24.0
six==1.15.0
spotipy==2.16.0
tqdm==4.49.0
urllib3==1.25.10
client_id="client token"
client_secret="client secret"
redirect_uri="http://localhost:8080"
Metallica - One
Rick Astley - Never Gonna Give You Up
@freakynit
Copy link

Awesome script. Minor fix if you have more than 100 songs (since spotify caps out 100 songs in one request).

Instead of:

# add found songs to playlist
print('Adding songs to playlist...')
playlist_id = playlists[0][1]  # get the first playlist matching the name
sp.playlist_add_items(playlist_id, song_ids)

use this:

# Function to split the song_ids list into chunks of size n
def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

# add found songs to playlist
print('Adding songs to playlist...')
playlist_id = playlists[0][1]  # get the first playlist matching the name
for chunk in chunks(song_ids, 10):
    time.sleep(1)
    print(f"Adding songs to playlist: {chunk}")
    sp.playlist_add_items(playlist_id, chunk)

Note: I have used chunks of 10 each. You can use up to 100.

Thanks to the OP for the awesome work 👏

@ttomasz
Copy link
Author

ttomasz commented Jan 15, 2024

Heh, thanks, it was just some one off script to show someone how to migrate playlist to spotify 😅 I'll add your loop to the code, thanks.

@freakynit
Copy link

Heh, thanks, it was just some one off script to show someone how to migrate playlist to spotify 😅 I'll add your loop to the code, thanks.

It's awesome nonetheless!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment