1

I am trying with the following code

cursor = connect.cursor()
    sqlSelect = "SELECT to_char(t.create_date, 'DD-MM-YYYY') AS CreatedDate,t.ticket_number AS TicketNo,p.name AS Priority,t.person_name AS Person,t.subject AS Subject,s.name AS State, to_char(t.close_date, 'DD-MM-YYYY') AS ClosedDate FROM website_support_ticket t INNER JOIN website_support_ticket_priority p ON p.id = t.priority_id INNER JOIN website_support_ticket_state s ON s.id = t.state_id ORDER BY CreatedDate"
    try:
        cursor.execute(sqlSelect)
        results = cursor.fetchall()
        headers = [i[0] for i in cursor.description]
        csvFile = csv.writer(open(filePath + fileName, 'w'),
                             delimiter=',', lineterminator='\r\n',
                             quoting=csv.QUOTE_ALL, escapechar='\\')

        csvFile.writerows(headers)
        csvFile.writerows(results)

When I print the headers Output is like

('headers', ['createddate', 'ticketno', 'priority', 'person', 'subject', 'state', 'closeddate'])

and headers just dont write into CSV like headers, Headers in CSV as of now

any suggestions how I can print the headers only on the top first row? As of now, every letter of header goes into different rows.

Any suggestion or fix would be really helpful.

1
  • @All, Any ways to apply bold format to headers? Commented Apr 16, 2021 at 13:07

2 Answers 2

4

Use writerow to add a single row passed as a list:

csvFile.writerow(headers)
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

headers = ", ".join(cursor.description)

Not sure if the cursor.description is passed back as a list or not.

So quick check on my own stuff and it comes back as a tuple. Which will screw up the above.

headers = ", ".join([i[0] for i in cursor.description])

2 Comments

Use hexbioc's solution, its neater than this
Yes @Amiga500, tried hexbioc's solution, it worked. Thank you for your efforts as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.