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

Python脚本调用返回CSV的REST API,无法本地保存文件求解决方案

解决Python调用REST API保存CSV文件的问题

基础解决方案(基于requests库)

根据API返回内容的类型,选择对应的写入方式:

情况1:API返回纯文本格式的CSV

如果返回的是未编码的CSV文本(比如直接显示逗号分隔的内容),用文本模式写入:

import requests

# 替换为你的API地址和本地保存路径
api_url = "https://example.com/api/export-csv"
save_path = "./output.csv"

# 发送请求(POST请求请替换为requests.post)
response = requests.get(api_url)
# 确保请求成功,失败则抛出异常
response.raise_for_status()

# 写入文件,编码根据实际情况调整(如utf-8、gbk)
with open(save_path, "w", encoding="utf-8") as csv_file:
    csv_file.write(response.text)

情况2:API返回二进制形式的CSV

如果API返回的是二进制流(响应头Content-Type为application/octet-stream或application/csv),用二进制模式写入:

import requests

api_url = "https://example.com/api/export-csv"
save_path = "./output.csv"

response = requests.get(api_url)
response.raise_for_status()

with open(save_path, "wb") as csv_file:
    csv_file.write(response.content)

常见问题排查

  • 权限问题:确保保存路径有写入权限,避免系统目录(如Windows的C:\),优先用用户目录或项目目录。
  • 认证缺失:如果API需要token或账号认证,在请求中添加headers:
    headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"}
    response = requests.get(api_url, headers=headers)
    
  • 乱码问题:如果写入后CSV乱码,手动指定响应编码:
    response.encoding = "gbk"  # 替换为API实际使用的编码
    with open(save_path, "w", encoding=response.encoding) as csv_file:
        csv_file.write(response.text)
    
  • 验证内容有效性:先打印response.text[:500]查看返回内容是否为合法CSV格式,排除API返回错误信息的可能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:55:22