Handling csv files with Python
Today my brother came with a problem of exporting a csv file to his mobile. Though the source is a csv file, the mobile software says its not a valid file. Later I found that, wrapping the values within double quotes could make the mobile software read the file correctly. A little search on the net has given the clue that python has csv module to do different operations on it.
So I have a file like below
test.csv
Name,Business Phone
John,0471232133
Joseph,94965123333
I have to convert it to something like
new.csv
Name,Business Phone
"John","0471232133"
"Joseph","94965123333"
The following python program could solve that
contact.py
import csv
fd = csv.reader(open("test.csv", "rb"))
for row in fd:
print row
wr = csv.writer(open("new.csv", "a"),quoting=csv.QUOTE_ALL)
wr.writerow(row)
# python contact.py
Read the csv module documentation for more info. The above program puts double quotes in the first line also. Modify it to suits your own needs. The above code is self explanatory.