Thursday, November 13, 2008

How to read and write the CSV file

We can do everything in Python mostly.today we'll show how to read and write csv file by Python.The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it.Python provide a lib which name csv to manipulate csv file.I think the best way to understand a new technology is an example,now let's see how to read a csv file.
#Python code:
import csv # first we need import necessary lib:csv
file=open("c:/Book1.csv") #prepare a csv file for our example

testReader=csv.reader(file,delimiter=' ', quotechar='|')
#now the testReader is an array,so we can iterate it
for row in testReader:
print "|".join(row)

#The result is:
Test1:Test1
Test2:Test2
.....

Mostly the value of a csv file will separate by comma,but sometime may be other App will generate a csv file and separate other quotechar(|,! etc).So csv lib provide a parameter :delimiter and quotechar, so you can custom it by yourself.
Now let's see how to write something into a csv file:
#Python code:
import csv # first we need import necessary lib:csv
file=open("c:/Book1.csv") #prepare a csv file for our example

testWriter = csv.writer(open('Book1.csv', 'w'), delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow(['Test'] * 5 + ['Wow'])
spamWriter.writerow(['Hello', 'I'm', 'Super Star'])


It's that easy,right?

1 comment:

dunnow said...

Hi Thanks for the post. I am trying to get the output of a csv file to display on a webpage using django. %s in html only makes it appear as a string. How do I get it to print rows as you did but on a webpage by reading the csv file?