Python3将TheMovieDB API结果保存至CSV的技术咨询
Solution: Save TMDB Movie Data to CSV (with Overwrite & Custom Columns)
Got it, let's get your script saving that movie data into a clean CSV file that overwrites old versions each time you run it. I'll cover all your requirements, including the optional custom column setup.
Updated Full Code
import http.client import json import csv # Your TMDB API key (keep this secure!) API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXX" # Connect to TMDB API and fetch data conn = http.client.HTTPSConnection("api.themoviedb.org") payload = "{}" conn.request( "GET", f"/3/discover/movie?page=20&include_video=false&include_adult=false&sort_by=primary_release_date.desc&language=en-US&api_key={API_KEY}", payload ) res = conn.getresponse() data = res.read() # Parse JSON response into Python dictionary movie_data = json.loads(data.decode("utf-8")) movies = movie_data["results"] # Define CSV columns (matches the fields from TMDB's response) csv_columns = [ "vote_count", "id", "video", "vote_average", "title", "popularity", "poster_path", "original_language", "original_title", "genre_ids", "backdrop_path", "adult", "overview", "release_date" ] # Save to CSV (overwrites existing file automatically) csv_filename = "daily_movies.csv" try: with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for movie in movies: # Convert lists (like genre_ids) to a comma-separated string for CSV readability if "genre_ids" in movie: movie["genre_ids"] = ", ".join(map(str, movie["genre_ids"])) writer.writerow(movie) print(f"Successfully saved {len(movies)} movies to {csv_filename}") except IOError as e: print(f"Error writing CSV file: {e}")
Key Features Explained
- CSV Saving: We use Python's built-in
csv.DictWriterwhich maps each movie's dictionary directly to the CSV columns you defined. No manual data formatting needed. - Overwrite Behavior: Opening the file with
'w'mode (write mode) automatically overwrites any existing file with the same name—no appending, no errors (as long as you have write permissions for the directory). - Custom Columns: The
csv_columnslist explicitly defines every column in your CSV, ensuring each movie's data lines up correctly. Even if a movie is missing a field (likeposter_pathbeingnull), it will leave that cell empty instead of breaking the CSV. - Readable Genre IDs: I added a quick conversion to turn the
genre_idslist into a comma-separated string (e.g.,[10751,28,12]becomes"10751, 28, 12"), which makes the CSV easier to read.
Quick Notes
- Make sure to replace
API_KEYwith your actual TMDB key. - If you want to fetch more pages later, you can wrap the API request in a loop that increments the
pageparameter and appends movies to themovieslist before writing to CSV. - The
encoding='utf-8'ensures non-English titles (like Japanese or German ones from your sample) save correctly without garbled text.
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

