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

请求协助将Python脚本输出结果保存为CSV文件

修改脚本将油价数据保存为CSV文件

我们可以通过Python内置的csv模块来实现将数据保存为CSV文件,替代原脚本的控制台输出。修改后的脚本如下:

import requests
import xml.etree.ElementTree as ET
import datetime
import csv  # 新增导入csv模块

response = requests.get('https://publicacionexterna.azurewebsites.net/publicaciones/prices')
myroot = ET.fromstring(response.content)

# 使用with语句打开CSV文件,自动处理文件关闭
with open('oil_prices.csv', 'w', newline='', encoding='utf-8') as csvfile:
    # 创建CSV写入对象
    writer = csv.writer(csvfile)
    # 写入表头
    writer.writerow(["Place_id", "Item", "Price", "Date"])
    
    for x in myroot.findall('place'):
        place_id = x.get('place_id')
        item = x.find('gas_price').attrib['type']
        price = x.find('gas_price').text
        today = datetime.date.today()
        # 写入每行数据
        writer.writerow([place_id, item, price, today])

关键修改说明:

  • 新增导入csv模块,利用专业工具处理CSV格式,避免手动拼接字符串可能出现的格式错误
  • 使用with语句打开文件,确保文件操作完成后自动关闭,提升代码安全性
  • 用csv.writer的writerow方法分别写入表头和每行数据,输出的CSV文件会自动处理字段分隔、编码等问题
  • 原有的数据获取逻辑完全保留,仅调整输出目标为本地CSV文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:10:31