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()
>Solution :
You can include the headers in the CSV file by modifying your code as follows:
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)