Google Colab挂载Drive后仍无法读取CSV文件及歌曲流派导出问题咨询
Fixing the FileNotFoundError in Your Spotify Genre Export Script
Hey there! Let's figure out why you're seeing that FileNotFoundError and get your script working properly. The main issue comes from inconsistent file paths in your code, plus a few other small tweaks we can make to avoid errors down the line.
What's Causing the Error?
You mounted Google Drive correctly, but your code is mixing absolute Drive paths and relative paths:
- You first open the file with the full Drive path:
/content/drive/MyDrive/regional-us-daily-latest.csv - But later in the loop, you try to read from
regional-us-daily-latest.csv(a relative path), which doesn't point to the file in your Drive. Colab's default working directory isn't your Drive folder, so it can't find the file here.
Additionally, there are a couple of other small issues that might cause problems later:
- Your loop logic for regions is a bit off (you're iterating over a single tuple instead of a list of region pairs)
- Directly modifying the DataFrame with
songs['Genre'][index]can lead to warnings or unexpected behavior - No error handling for Spotify API calls (if an artist isn't found, your script will crash)
Step-by-Step Fixes
1. Confirm Your File Path
First, double-check the exact path to your CSV:
- In Colab's left sidebar, expand
Drive > MyDrive - Find
regional-us-daily-latest.csv, right-click it, and select Copy path - Paste this path somewhere safe—we'll use it in the script
2. Updated Working Code
Here's the fixed version of your script with explanations of key changes:
!pip3 install spotipy import pandas as pd import spotipy from spotipy.oauth2 import SpotifyClientCredentials from google.colab import drive, files # Mount Google Drive (run this once per session) drive.mount('/content/drive') # Spotify API credentials client_id = 'YOUR_CLIENT_ID' # Replace with your actual ID client_secret = 'YOUR_CLIENT_SECRET' # Replace with your actual secret client_credentials_manager = SpotifyClientCredentials(client_id, client_secret) spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager) # Define regions with FULL Drive paths for input files regions = [ ("/content/drive/MyDrive/regional-us-daily-latest.csv", "us.csv") ] for input_path, output_file in regions: # Read the CSV with the full Drive path songs = pd.read_csv(input_path, index_col=0, header=1) songs = songs.assign(Genre="") # Initialize Genre column as empty string for index, row in songs.iterrows(): artist = row["Artist"] try: # Search for the artist, handle cases where no results are found result = spotify.search(artist, limit=1, type="artist") if result["artists"]["items"]: genres = result["artists"]["items"][0]["genres"] # Use .loc to safely update the DataFrame songs.loc[index, "Genre"] = ', '.join(genres) # Convert genre list to string for CSV else: songs.loc[index, "Genre"] = "No genre found" except Exception as e: songs.loc[index, "Genre"] = f"Error: {str(e)}" print(f"Error processing {artist}: {e}") # Show first 10 rows to verify print("Preview of processed data:") print(songs.head(10)) # Save to CSV and download songs.to_csv(output_file) files.download(output_file)
Key Changes Made:
- Consistent absolute paths: We use the full Drive path for the input CSV so Colab can always find it
- Improved loop structure:
regionsis a list of tuples, making it easy to add more regions later if needed - Safe DataFrame updates: Using
songs.loc[index, "Genre"]instead of direct indexing avoids pandas warnings - Error handling: Wrapped the Spotify API call in a
try/exceptblock to catch issues like missing artists or API errors - Genre formatting: Converted the list of genres to a comma-separated string so it saves cleanly in CSV format
- Removed unused code: The initial
csvfile = open(...)line was redundant since we use pandas to read the CSV, so we removed it
Final Checks
- Make sure your Spotify
client_idandclient_secretare correctly entered (no curly quotes—use straight quotes like'or") - After running the script, check the left sidebar's
Filestab for the outputus.csv(it will be in Colab's default working directory unless you specify a Drive path for it)
内容的提问来源于stack exchange,提问作者Matchamin
相关产品推荐
相关产品推荐

