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

如何使用Python从MySQL导出包含表头的CSV文件?

给MySQL导出的CSV添加表头

要导出带表头的CSV,核心是从游标中提取表的列名,先写入表头再写入数据,修改后的代码如下:

import csv

# 原有SQL执行逻辑
sql_data = "select * from ETSY_seller where Crawl_Date='2022-12-14' and Cohort = '418k'"
sql_cursor.execute(sql_data, multi=True)
data = sql_cursor.fetchall()

# 从游标元数据中提取表头
headers = [desc[0] for desc in sql_cursor.description]

# 打开文件时添加newline=''避免空行问题
fp = open('/home/ec2-user/TV_eCommerce/US/extra/cohort418k_20221214.csv', 'w', newline='')
myFile = csv.writer(fp)

# 先写入表头,再写入数据
myFile.writerow(headers)
myFile.writerows(data)

fp.close()

关键改动说明

  • 利用sql_cursor.description获取结果集的元数据,其中每个元素的第一个值对应数据库表的列名,通过列表推导式整理成表头列表
  • 打开文件时追加newline='',避免部分系统下导出的CSV出现多余空行
  • 先调用writerow()写入单行表头,再用writerows()批量写入数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:57:03