如何使用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
相关产品推荐
相关产品推荐

