Writing to CSV file


In this post we are going to write some data to csv file. For this, you have to install csv module if its not installed. To check if its installed in python interpreter type import csv. If it gives error 'ImportError: No module named csv'. Then you have to install it. Your favorite installer pip can be a good way to go.
try:
    import csv
except ImportError:
    print "csv module not installed"
a=[1,2,3,4,5]
b=['Hulk','Iron Man','SpiderMan','Batman','Super Man']
f=open('superhero.csv','a+')
writer=csv.writer(f)
writer.writerow(['Id','Name'])
for (ind,val) in zip(a,b):
    writer.writerow([ind,val])
f.close()
First four line does import csv module,if its not installed it prints the error 'csv module not installed'. Now a and b has the data we will be writing to csv file. For your case you may get the data from database. Now we have a new file superhero.csv file created in the fourth line. then we create an writer variable using writer function of csv module. We write the first row as Id,Name. The we loop through each of the elements in a and b after zipping them to write to the file.Finally we close the file.And the final output in the file looks like:
Id,Name
1,Hulk
2,Iron Man
3,SpiderMan
4,Batman
5,Super Man

Comments

Popular posts from this blog

Automate file upload in Selenium IDE

How To Install and Configure Nextcloud