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

CSV关联Python地址解析代码报错IndexError: List index out of range求助

解决IndexError: List index out of range及代码逻辑问题

嘿,咱们先把问题拆解清楚:

首先,你碰到的IndexError: List index out of range几乎肯定是出在data['results'][0]这一行。当Google Geocoding API找不到你传入地址的匹配结果时,data['results']会变成一个空列表,这时候你硬要访问索引0,自然就会报错。

另外你的代码逻辑还有几个和你描述的CSV结构不匹配的地方:

  • 你说CSV里URL在A[1]列、名称在A[2]列,但你用了csv.DictReader——如果你的CSV没有表头行,DictReader会把第一行数据当成表头,这时候row["URL"]根本取不到正确的值;如果有表头,那表头得正好是"URL"和对应名称列的字段名才行。
  • 你把row["URL"]拆分行后又用csv.reader读取,这完全是逻辑混淆了——你要的是用名称去请求位置信息,不是把URL当成CSV来解析啊。

下面是修正后的代码,同时加了完整的错误处理,避免各种意外情况:

import requests
import csv

# API端点
URL = "http://maps.googleapis.com/maps/api/geocode/json"

# 使用with语句管理文件,自动关闭更安全
with open("z1.csv", newline='', encoding='utf-8') as f:
    # 如果你CSV有表头(比如第一行是"URL", "名称"),用DictReader;如果没有表头,换成reader = csv.reader(f)
    reader = csv.DictReader(f)
    for row in reader:
        # 替换成你CSV里名称列的实际表头(如果是无表头的情况,改成row[2],因为A[2]是第三列,索引从0开始)
        location = row["名称"]
        if not location:
            print("跳过空的名称字段")
            continue
        
        print(f"正在处理名称: {location}")
        
        PARAMS = {'address': location}
        try:
            # 发送请求并捕获HTTP错误
            r = requests.get(url=URL, params=PARAMS)
            r.raise_for_status()
            
            data = r.json()
            
            # 先检查API有没有返回结果
            if not data.get('results'):
                error_msg = data.get('error_message', '无具体错误信息')
                print(f"无法找到{location}的位置信息,API提示: {error_msg}")
                continue
            
            # 提取位置数据
            result = data['results'][0]
            latitude = result['geometry']['location']['lat']
            longitude = result['geometry']['location']['lng']
            formatted_address = result['formatted_address']
            
            print(f"Latitude: {latitude}\nLongitude: {longitude}\nFormatted Address: {formatted_address}\n")
        except requests.exceptions.RequestException as e:
            print(f"请求API时出错: {e}")
        except KeyError as e:
            print(f"解析API返回数据时出错,缺少必要字段: {e}")

关键修正点说明:

  1. 错误防护:
    • 检查名称字段是否为空,避免无效请求
    • 捕获网络请求异常(比如断网、API限流)
    • 先判断data['results']是否为空,彻底解决索引越界问题
  2. 逻辑对齐:
    • 直接使用CSV中的名称字段作为地址请求API,去掉了多余的无效CSV解析步骤
    • 明确了CSV表头/无表头的使用方式,你可以根据自己的文件结构调整
  3. 代码健壮性:
    • 使用with语句管理文件,避免资源泄漏
    • 用f-string代替旧式格式化,可读性更好

内容的提问来源于stack exchange,提问作者kasheesh kashi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:05:18