Python Top Artists From Last.fm CSV

This python example script will get the top 1,000 artists from last.fm and save it as a CSV file. Just add your API key and desired file path.

########################################
import os, sys, re, datetime, traceback, urllib2, urllib
import xml.etree.ElementTree as etree

API_KEY = ""
OUTPUT_FILEPATH = ".csv"

last_fm_top_artists_url = "http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=%s&limit=1000" \
% API_KEY
last_fm_top_artists_feed_request = urllib2.Request(last_fm_top_artists_url)
last_fm_top_artists_opener = urllib2.build_opener()
last_fm_top_artists_xml_file = last_fm_top_artists_opener.open(last_fm_top_artists_feed_request)
last_fm_top_artists_tree = etree.parse(last_fm_top_artists_xml_file)
last_fm_top_artists_root = last_fm_top_artists_tree.getroot()

artists_node = last_fm_top_artists_root.find("artists")
artists = artists_node.getiterator("artist")
f = open(OUTPUT_FILEPATH, "w")
for artist in artists:
    f.write(artist.find('name').text.encode('utf-8'))
    f.write('\n')
f.close()
print "COMPLETED"

Baskets