Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Save data along with headers My Sql python

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading