Python3从CoinGecko API获取JSON数据并转换为CSV文件报错求助
Hey there, let's work through this issue step by step to get your CSV output working correctly:
1. What's Causing the TypeError?
The error TypeError: can only concatenate list (not "str") to list pops up because you're trying to directly add a list (prices is a list of lists) to a string (","). Python doesn't allow mixing these types in concatenation—you need to convert list values to strings first.
2. Your Loop Logic is Misaligned
When you run for market in cont, you're actually iterating over the keys of the dictionary ('prices', 'market_caps', 'total_volumes'), not the individual data points. Every loop iteration just grabs the entire three lists again, which isn't what you want. You need to pair up corresponding entries from each list (since each index in prices, market_caps, and total_volumes refers to the same timestamp).
Fixed Code Option 1: Manual String Formatting
We'll use zip() to iterate over all three lists in parallel, then format each data point into clean CSV rows:
import json import urllib.request url = 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1&interval=daily&sparkline=false' req = urllib.request.Request(url) # Use a context manager to auto-close the file with open("coingecko1.csv", "w", encoding="utf8") as myfile: # Update headers to reflect actual data columns headers = "Timestamp,Price,Market_Cap,Total_Volume\n" myfile.write(headers) r = urllib.request.urlopen(req).read() cont = json.loads(r.decode('utf-8')) # Zip the three lists to get matching timestamp entries for price_entry, cap_entry, vol_entry in zip(cont["prices"], cont["market_caps"], cont["total_volumes"]): timestamp = price_entry[0] price = price_entry[1] market_cap = cap_entry[1] total_volume = vol_entry[1] # Format each row as a string (f-strings handle type conversion automatically) row = f"{timestamp},{price},{market_cap},{total_volume}\n" myfile.write(row) print("job complete")
Fixed Code Option 2: Using Python's csv Module (Recommended)
For more robust CSV handling (like automatically escaping special characters), use Python's built-in csv module:
import json import urllib.request import csv url = 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=1&interval=daily&sparkline=false' req = urllib.request.Request(url) r = urllib.request.urlopen(req).read() cont = json.loads(r.decode('utf-8')) with open("coingecko1.csv", "w", encoding="utf8", newline='') as myfile: writer = csv.writer(myfile) # Write descriptive header row writer.writerow(["Timestamp", "Price", "Market_Cap", "Total_Volume"]) # Write each data row by pairing corresponding entries for price_entry, cap_entry, vol_entry in zip(cont["prices"], cont["market_caps"], cont["total_volumes"]): writer.writerow([price_entry[0], price_entry[1], cap_entry[1], vol_entry[1]]) print("job complete")
Key Improvements:
- Parallel Iteration:
zip()ensures we grab matching timestamp entries from all three lists at once. - Proper Type Handling: We extract individual values and let f-strings or the
csvmodule handle type conversion, avoiding list-string concatenation errors. - Cleaner Headers: Updated headers to clearly describe each column instead of vague labels.
- Safe File Handling: Using
with open(...)ensures the file is closed properly after writing, even if an error occurs.
内容的提问来源于stack exchange,提问作者Lee

