#!/usr/bin/env python # Spotify URI list to CSV with track information # by blha303 # Licensed under the Mozilla Public License 2.0 https://www.mozilla.org/MPL/2.0/ # Tested under Python 2.7.3. Small changes may need to be made to be backwards-compatible. # Usage: spCSVParse.py # Select songs from a playlist in Spotify, right click when they're all selected, # click Copy Spotify URI, then paste in after 'spCSVParse.py '. # Alternatively, a file called playlists in the same folder # This file can contain other lines (e.g. section headings) if desired. The script # only parses lines starting with 'spotify:track' or 'spotify:local' # If you're making the playlists file by pasting from Spotify, make sure to: # 1. set the linebreaks to \n instead of \r\n (also known as UNIX mode, as opposed # to Windows mode) # 2. replace all spaces with \n. I did this by replacing " spotify" with "\nspotify" # If you have questions about this file, ask below, or on irc.esper.net #blha303 import json from urllib import urlopen import sys import codecs import time def getJson(uri): data = urlopen("http://ws.spotify.com/lookup/1/.json?uri=%s" % uri).read() datad = json.loads(data) if datad["info"]["type"] != "track": #validating print "Invalid api reply for " + s sys.exit() return datad def csvEscape (s): if "," in s: s.replace(',', '""') s = '"' + s + '"' return s content = sys.argv[1:] if content == []: f = codecs.open("playlists", "r", "utf-8") content = f.readlines() f.close() nf = codecs.open("output.csv", "w", "utf-8") starttime = time.time() print "Started at " + str(int(starttime)) for s in content: if s[:13] == "spotify:track": datad = getJson(s) name = csvEscape(datad["track"]["name"]) artist = csvEscape(datad["track"]["artists"][0]["name"]) album = csvEscape(datad["track"]["album"]["name"]) output = artist + "," + name + "," + album nf.write(output + "\n") print s.replace("\n", "") + " : " + output elif s[:13] == "spotify:local": out = s.replace("spotify:local:", "").split(":") artist = csvEscape(out[0].replace("+", " ")) album = csvEscape(out[1].replace("+", " ")) name = csvEscape(out[2].replace("+", " ")) output = artist + "," + name + "," + album nf.write(output + "\n") print s.replace("\n", "") + " : " + output else: print s.replace("\n", "") if "\n" in s: nf.write(s) else: nf.write(s + "\n") nf.close() endtime = time.time() print "Completed at " + str(int(endtime)) duration = endtime - starttime print "Process completed in " + str(int(duration)) + " seconds"