英文:
Save data along with headers My Sql python
问题
将 CSV 文件与标题一起保存。
以下是我正在使用的代码,但在这里我只得到了数据部分,没有标题部分。
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()
fp = open('/home/ec2-user/TV_eCommerce/US/extra/cohort418k_20221214.csv', 'w')
myFile = csv.writer(fp)
myFile.writerows(data)
fp.close()
英文:
How to Save the csv file along with headers.
Below is the code which I am using but here I am getting only data not the headers part.
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()
fp = open('/home/ec2-user/TV_eCommerce/US/extra/cohort418k_20221214.csv', 'w')
myFile = csv.writer(fp)
myFile.writerows(data)
fp.close()
答案1
得分: 1
以下是代码的中文翻译:
# 修改您的代码以在 CSV 文件中包含标题:
import csv
import mysql.connector
# 建立数据库连接和游标
mydb = mysql.connector.connect(
host="your_host", # 您的主机
user="your_username", # 您的用户名
password="your_password", # 您的密码
database="your_database" # 您的数据库名称
)
mycursor = mydb.cursor()
# 执行 SQL 查询以获取数据和标题
sql = "SELECT * FROM ETSY_seller WHERE Crawl_Date='2022-12-14' and Cohort = '418k'"
mycursor.execute(sql)
headers = [i[0] for i in mycursor.description] # 获取列标题
data = mycursor.fetchall()
# 将数据和标题写入 CSV 文件
with open('/home/ec2-user/TV_eCommerce/US/extra/cohort418k_20221214.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
writer.writerows(data)
如果您有其他需要,请告诉我。
英文:
You can include the headers in the CSV file by modifying your code as follows:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import csv
import mysql.connector
# establish database connection and cursor
mydb = mysql.connector.connect(
host="your_host",
user="your_username",
password="your_password",
database="your_database"
)
mycursor = mydb.cursor()
# execute SQL query to fetch data and headers
sql = "SELECT * FROM ETSY_seller WHERE Crawl_Date='2022-12-14' and Cohort = '418k'"
mycursor.execute(sql)
headers = [i[0] for i in mycursor.description] # get column headers
data = mycursor.fetchall()
# write data and headers to CSV file
with open('/home/ec2-user/TV_eCommerce/US/extra/cohort418k_20221214.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
writer.writerows(data)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论