I have a Tuple result from mysql like this :
sqlResult=({'Count': 1L, 'gname': 'Anron may'}, {'Count': 1L, 'gname': 'Anchy de'}, {'Count': 1L, 'gname': 'abby ras'}, {'Count': 2L, 'gname': 'Akki nome'}, {'Count': 41L, 'gname': 'Archenemy'}, {'Count': 1L, 'gname': 'Antony papa'}, {'Count': 1L, 'gname': 'Dead zombie'})
I am trying to save this data to CSV file like this
import time
csvName="Gnames-and-count-"+str(int(time.time()))
csvPath="/home/sean/Desktop/"+str(csvName)+str(".csv")
writer = csv.writer(open(csvPath, 'wt'))
for results in sqlResult:
writer.writerow([results['gname'],int(results['Count'])])
The file is created at the following path but nothing is there on the file. Is there any obvious thing i am missing? .Please guide me.
You need to close the file. Let with
do it for you.
with open(csvPath, 'w') as f:
writer = csv.writer(f)
for results in sqlResult:
writer.writerow([results['gname'],int(results['Count'])])
Instead of directly write into csv file write into standard out put and saves the result in file_name.csv
import csv
import sys
...
...
writer=csv.writer(sys.stdout)
...
then for taking output in csv
you can write command like this :-
$ program_name > my_spreadsheet.csv
Hope it will help you...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.