-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspotify-export.py
More file actions
88 lines (73 loc) · 2.97 KB
/
Copy pathspotify-export.py
File metadata and controls
88 lines (73 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
import csv
# Spotify API credentials (Replace with your details)
CLIENT_ID = "<CLIENT ID>"
CLIENT_SECRET = "<CLIENT_SECRET>"
REDIRECT_URI = "<REDIRECT URI>"
# Set up authentication
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope="playlist-read-private user-library-read"
))
### Function to extract playlist tracks ###
def get_playlist_tracks(playlist_id, playlist_name):
tracks = []
results = sp.playlist_tracks(playlist_id)
while results:
for item in results['items']:
track = item.get('track') # Avoid KeyError if track is missing
if track and track.get('name'):
tracks.append({
'Type': 'Playlist',
'Playlist': playlist_name,
'Artist': ', '.join([artist['name'] for artist in track.get('artists', [])]),
'Album': track.get('album', {}).get('name', ''),
'Title': track.get('name', ''),
'Track ID': track.get('id', ''),
'Track URL': track.get('external_urls', {}).get('spotify', '')
})
else:
print(f"Warning: Skipping track due to missing data in {playlist_name}")
results = sp.next(results) if results else None # Handle pagination
return tracks
### Function to extract saved albums ###
def get_saved_albums():
albums = []
results = sp.current_user_saved_albums()
while results:
for item in results['items']:
album = item.get('album')
if album:
albums.append({
'Type': 'Saved Album',
'Playlist': '',
'Artist': ', '.join([artist['name'] for artist in album.get('artists', [])]),
'Album': album.get('name', ''),
'Title': '', # No specific track title for albums
'Track ID': album.get('id', ''),
'Track URL': album.get('external_urls', {}).get('spotify', '')
})
results = sp.next(results) if results else None # Handle pagination
return albums
### Main execution ###
all_tracks = []
# Extract all playlists
playlists = sp.current_user_playlists()
for playlist in playlists['items']:
playlist_name = playlist['name']
playlist_id = playlist['id']
print(f"Extracting playlist: {playlist_name}...")
all_tracks.extend(get_playlist_tracks(playlist_id, playlist_name))
# Extract saved albums
print("Extracting saved albums...")
all_tracks.extend(get_saved_albums())
# Convert to DataFrame
df = pd.DataFrame(all_tracks)
# Save as UTF-8 CSV with correct formatting
csv_filename = "spotify_playlists_and_albums.csv"
df.to_csv(csv_filename, index=False, encoding="utf-8-sig", quoting=csv.QUOTE_ALL)
print(f"✅ Export complete! Data saved as '{csv_filename}'.")