import json import csv from pathlib import Path # --- CONFIGURATION --- # Replace this with the path to your folder. # The script will read JSONs from here AND save the CSV. BASE_PATH = 'C:/temp/spotify/' # <-- Change this to your actual folder path OUTPUT_FILENAME = 'C:/temp/spotify_history.csv' DELIM = ';' # Delimiter for CSV, change if needed def spotify_json_to_csv(): # Create a Path object from the global variable work_dir = Path(BASE_PATH) output_path = OUTPUT_FILENAME # Open the CSV file for writing with open(output_path, 'w', newline='', encoding='utf-8') as csv_out: writer = csv.writer(csv_out, delimiter=DELIM) # Write the header row with the new column writer.writerow(['Timestamp', 'Song Title', 'Artist', 'ms_played']) print(f"Scanning: {work_dir}") print(f"Output will be saved to: {output_path}") # Walk through all JSON files in the directory for file_path in work_dir.glob('**/*.json'): # Skip the output file itself if it already exists to avoid errors if file_path.name == OUTPUT_FILENAME: continue try: with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) print( f"Processing: {file_path.name} with {len(data)} entries") if isinstance(data, list): for entry in data: timestamp = entry.get('ts') song = entry.get('master_metadata_track_name') artist = entry.get( 'master_metadata_album_artist_name') ms_played = entry.get('ms_played', 0) # Write row only if we have a valid song title if song: writer.writerow( [timestamp, song, artist, ms_played]) except json.JSONDecodeError: print(f"Warning: Could not decode {file_path.name}") except Exception as e: print(f"Error processing {file_path.name}: {e}") print("Done!") if __name__ == "__main__": spotify_json_to_csv()