#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:
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?
Post a Comment