-1

I am fairly new to python and I have started working/creating different projects.

In a project I'm using Spotipy to grab an artists discography. I have the code below that grabs the artist information and calls another function show_album_tracks

def show_artist_albums(id):
    albums = []
    results = sp.artist_albums(artist['id'], album_type='album')
    albums.extend(results['items'])
    while results['next']:
        results = sp.next(results)
        albums.extend(results['items'])
    print('Total albums:', len(albums))
    unique = set()  # skip duplicate albums
    for album in albums:
        name = album['name'].lower()
        if name not in unique:
            print(name)
            unique.add(name)
            show_album_tracks(album)

In show_album_tracks it prints the below track list

def show_album_tracks(album):
    tracks = []
    results = sp.album_tracks(album['id'])
    #print(results)
    tracks.extend(results['items'])
    while results['next']:
        results = sp.next(results)
        tracks.extend(results['items'])
    for track in tracks:
        print('  ', track['name'])
        print()
        print(track)

So tracks contains the information I would like to put into a csv. Whats the best method for exporting? I tried creating a dataframe within the function but it prints out empty. Any help is appreciated. Any other links to help read and understand the structure is appreciated as well

see the output snippet below:

{'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/06HL4z0CvFAxyc27GXpf02'}, 'href': 'https://api.spotify.com/v1/artists/06HL4z0CvFAxyc27GXpf02', 'id': '06HL4z0CvFAxyc27GXpf02', 'name': 'Taylor Swift', 'type': 'artist', 'uri': 'spotify:artist:06HL4z0CvFAxyc27GXpf02'}], 'available_markets': ['AD', 'AE', 'AR', 'AT', 'AU', 'BE', 'BG', 'BH', 'BO', 'BR', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'DZ', 'EC', 'EE', 'EG', 'ES', 'FI', 'FR', 'GB', 'GR', 'GT', 'HK', 'HN', 'HU', 'ID', 'IE', 'IL', 'IN', 'IS', 'IT', 'JO', 'JP', 'KW', 'LB', 'LI', 'LT', 'LU', 'LV', 'MA', 'MC', 'MT', 'MX', 'MY', 'NI', 'NL', 'NO', 'NZ', 'OM', 'PA', 'PE', 'PH', 'PL', 'PS', 'PT', 'PY', 'QA', 'RO', 'SA', 'SE', 'SG', 'SK', 'SV', 'TH', 'TN', 'TR', 'TW', 'US', 'UY', 'VN', 'ZA'], 'disc_number': 1, 'duration_ms': 170640, 'explicit': False, 'external_urls': {'spotify': 'https://open.spotify.com/track/43rA71bccXFGD4C8GOpIlN'}, 'href': 'https://api.spotify.com/v1/tracks/43rA71bccXFGD4C8GOpIlN', 'id': '43rA71bccXFGD4C8GOpIlN', 'is_local': False, 'name': 'I Forgot That You Existed', 'preview_url': None, 'track_number': 1, 'type': 'track', 'uri': 'spotify:track:43rA71bccXFGD4C8GOpIlN'}
   Cruel Summer

{'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/06HL4z0CvFAxyc27GXpf02'}, 'href': 'https://api.spotify.com/v1/artists/06HL4z0CvFAxyc27GXpf02', 'id': '06HL4z0CvFAxyc27GXpf02', 'name': 'Taylor Swift', 'type': 'artist', 'uri': 'spotify:artist:06HL4z0CvFAxyc27GXpf02'}], 'available_markets': ['AD', 'AE', 'AR', 'AT', 'AU', 'BE', 'BG', 'BH', 'BO', 'BR', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'DZ', 'EC', 'EE', 'EG', 'ES', 'FI', 'FR', 'GB', 'GR', 'GT', 'HK', 'HN', 'HU', 'ID', 'IE', 'IL', 'IN', 'IS', 'IT', 'JO', 'JP', 'KW', 'LB', 'LI', 'LT', 'LU', 'LV', 'MA', 'MC', 'MT', 'MX', 'MY', 'NI', 'NL', 'NO', 'NZ', 'OM', 'PA', 'PE', 'PH', 'PL', 'PS', 'PT', 'PY', 'QA', 'RO', 'SA', 'SE', 'SG', 'SK', 'SV', 'TH', 'TN', 'TR', 'TW', 'US', 'UY', 'VN', 'ZA'], 'disc_number': 1, 'duration_ms': 178426, 'explicit': False, 'external_urls': {'spotify': 'https://open.spotify.com/track/1BxfuPKGuaTgP7aM0Bbdwr'}, 'href': 'https://api.spotify.com/v1/tracks/1BxfuPKGuaTgP7aM0Bbdwr', 'id': '1BxfuPKGuaTgP7aM0Bbdwr', 'is_local': False, 'name': 'Cruel Summer', 'preview_url': None, 'track_number': 2, 'type': 'track', 'uri': 'spotify:track:1BxfuPKGuaTgP7aM0Bbdwr'}
   Lover
  • _I tried creating a dataframe within the function but it prints out empty._ Where is that code? _So tracks contains the information I would like to put into a csv. Whats the best method for exporting?_ Stack Overflow is not a free code writing service, nor is it meant to provide personalized guides and tutorials. See: [ask], [help/on-topic], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users. – AMC Mar 16 '20 at 19:07
  • Speaking of reading, have you done any yourself? https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python?noredirect=1&lq=1. What about the rest of my comment? – AMC Mar 16 '20 at 19:58
  • I'm not opposed to any of that, but the way you phrase it is unnecessary and most people on here are new, and just trying to learn. – MyFriendBobSacamano Mar 16 '20 at 20:06

2 Answers2

1

If you post your output it would be easy to identify. but any way you can try below code

 csv_file = open(output_file, "w")
 writer = csv.writer(csv_file, delimiter=',', lineterminator="\n", 
                      quoting=csv.QUOTE_NONNUMERIC)
 for track in tracks:
   writer.writerow(track)

or directly you can append to list

 writer.writerow(tracks)
Community
  • 1
  • 1
1

The easiest option to manage dataframes is Pandas.

I dont know what do you have in your lists. In any case pandas allow you to create dataframes from lists:

import pandas as pd
dataframe = pd.DataFrame([1,2,3],[4,5,6]], columns=['col1', 'col2', 'col3'])

   col1  col2  col3
0     1     2     3
1     4     5     6

Where I wrote the lists you should insert your own lists. Every list as you can see makes a row, but you can also add them as columns:

df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
                   'mask': ['red', 'purple'],
                   'weapon': ['sai', 'bo staff']})

Then if you want to export it as csv you only have to use the method to_csv()

You can pass the method arguments to write it directly to your disk: pandas doc