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

Python 2.7重定向Google Maps API输出到文件时遇UnicodeEncodeError

解决UnicodeEncodeError:写入含非ASCII字符的CSV文件

这个错误的核心原因是你打开文件时用了默认的ASCII编码,而Google Maps返回的地址包含非ASCII字符(比如你遇到的ó),ASCII编码无法处理这些字符,所以抛出了编码错误。下面给你两种可行的解决办法:

方法1:指定文件编码为UTF-8

直接在打开文件时指定encoding='utf-8'参数,让文件以UTF-8编码写入,就能兼容所有非ASCII字符了。另外注意把Google Maps客户端的初始化放在循环外,避免重复创建连接浪费资源:

Python 3版本修改后的代码:

import googlemaps
from __future__ import print_function

# 打开文件时明确指定UTF-8编码
with open('output.csv', 'w', encoding='utf-8') as f:
    gmaps = googlemaps.Client(key="my_key")
    for idx, row in df.iterrows():
        reverse_result = gmaps.reverse_geocode((row['lat'], row['lon']), result_type='administrative_area_level_3')
        for result in reverse_result:
            # 用sep指定分隔符,避免字段内的空格干扰CSV格式
            print(row['object'], result["formatted_address"], sep=',', file=f)

Python 2版本修改后的代码:

如果你的环境是Python 2,需要用codecs模块来处理编码:

import googlemaps
import codecs
from __future__ import print_function

# 使用codecs打开UTF-8编码的文件
with codecs.open('output.csv', 'w', encoding='utf-8') as f:
    gmaps = googlemaps.Client(key="my_key")
    for idx, row in df.iterrows():
        reverse_result = gmaps.reverse_geocode((row['lat'], row['lon']), result_type='administrative_area_level_3')
        for result in reverse_result:
            # Python 2中需手动将unicode转为utf-8字节流
            print(row['object'].encode('utf-8'), result["formatted_address"].encode('utf-8'), sep=',', file=f)

方法2:使用Python内置的csv模块(更推荐)

手动用print写入CSV容易踩坑——比如地址里包含逗号、引号时,会破坏CSV的格式。用csv模块可以自动处理这些特殊情况,同时完美解决编码问题:

import googlemaps
import csv
from __future__ import print_function

gmaps = googlemaps.Client(key="my_key")

# 打开文件并初始化csv写入器
with open('output.csv', 'w', encoding='utf-8', newline='') as f:
    writer = csv.writer(f)
    # 可选:写入表头,让CSV结构更清晰
    writer.writerow(['object', 'formatted_address'])
    for idx, row in df.iterrows():
        reverse_result = gmaps.reverse_geocode((row['lat'], row['lon']), result_type='administrative_area_level_3')
        for result in reverse_result:
            writer.writerow([row['object'], result["formatted_address"]])

这种方式不仅解决了编码错误,还能保证CSV文件的格式合法性,比如遇到带逗号的地址时,模块会自动用双引号包裹字段,避免后续解析CSV时出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:57:56