user2470026
user2470026

Reputation: 157

formatted output like this in python

Here is the python code with the query to the database

cursor.execute("""select count(distinct offering_name) as events
,count(learner) as learners 
,count(distinct learner) as unique_learner
,count(dropped) as dropped
,sum(trans_price) as trans_price
from EMS_data where organization like 'eng%' and manager ='rakesh'""")

for result in cursor: print result

the result will be like this and what does the "L" means

(367L, 7200L, 4543L, 7200L, 3216157.0)

but i want to like this

| events | learners | unique_learner | dropped | trans_price |

| 378 | 8092 | 5204 | 8092 | 3197704.0799999996 |

how can do in this way... Please help

Upvotes: 1

Views: 78

Answers (1)

alecxe
alecxe

Reputation: 473843

Looks like you need an output in csv format. And you can get column names from cursor.description.

Try this:

with open('test.csv', 'w') as f:
    writer = csv.writer(f, delimiter="|")
    csv.writerow([col[0] for col in cursor.description])
    for result in cursor:
        writer.writerow(result)

test.csv:

events|learners|unique_learner|dropped|trans_price
367|7200|4543|7200|3216157.0

Alternatively, instead of using csv module, you can use string formatting as @Mr E suggested, or just join values via " | ".join(...).

Hope that helps.

Upvotes: 1

Related Questions