You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3从CoinGecko API获取JSON数据并转换为CSV文件报错求助

Fixing Your CoinGecko API to CSV Conversion Error

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")

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 csv module 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:52:48