import json import requests import pandas as pd from pandas import DataFrame from pprint import pprint import datetime import base64 import sys import csv import urllib with open('artists_over_100.csv', 'rt') as f: reader = csv.reader(f) all_artists = list(reader) def get_creds(): client_id = 'your-client-id' client_secret = 'your-client-secret' access_token = None client_credentials = client_id + ':' + client_secret base = base64.b64encode(client_credentials.encode('ascii')) payload = {'grant_type': 'client_credentials'} headers = {'Authorization': 'Basic {}'.format(base.decode('utf-8'))} r = requests.post( 'https://accounts.spotify.com/api/token', data=payload, headers=headers) json_response = r.json() access_token = json_response['access_token'] print(access_token) auth = "Bearer " + access_token cred_time = datetime.datetime.now() return auth, cred_time def get_placements(): auth, cred_time = get_creds() new_tracks = [] with open('artists_over_100_with_genres.csv', 'wb') as myfile: for artist in all_artists[1:]: current_time = datetime.datetime.now() if (current_time - cred_time).total_seconds() >2500: auth, cred_time = get_creds() print(auth) a = urllib.quote(artist[0]) #below is to get playlist info f_response = requests.get('https://api.spotify.com/v1/search?q=' + a + '&type=artist', headers={"Authorization": auth}) f_data = f_response.json() if f_data.get("error"): if f_data.get("error").get("status") == 404: print("Something went wrong.") continue elif f_data.get("error").get("status") == 401: print("key error 401") break elif f_data.get("error").get("status") == 403: print("key error 403") break else: if len(f_data.get("artists").get("items")) == 0: pass else: genres = f_data.get("artists").get("items")[0].get("genres") genres.insert(0,artist[0]) print genres wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(genres) def main(): get_placements() print("Done.") main()