Reading and Writing CSV Files with Python
Reading CSV files can be a real pain, especially when the file is badly formatted. Accounting for badly formatted files can be difficult and can cause a lot of headaches.
Python has a very useful library to help with parsing and writing CSV files. The library is not totally full proof, but it does account for almost ever possible problem, plus it correctly writes CSV files.
The following is an example of how to read a CSV file:
import csv
reader = csv.reader(open("test.csv"), delimiter=",")
for column1, column2, column3 in reader:
print column1, column2
The next example shows how to write a CSV file from an array variable:
import csv
import sys
data = [
("And Now For Something Completely Different", 1971, "Ian MacNaughton"),
("Monty Python And The Holy Grail", 1975, "Terry Gilliam, Terry Jones"),
("Monty Python's Life Of Brian", 1979, "Terry Jones"),
("Monty Python Live At The Hollywood Bowl", 1982, "Terry Hughes"),
("Monty Python's The Meaning Of Life", 1983, "Terry Jones")
]
writer = csv.writer(open("test.csv"), delimiter=",")
for item in data:
writer.writerow(item)
OR
import csv
import sys
data = [
("And Now For Something Completely Different", 1971, "Ian MacNaughton"),
("Monty Python And The Holy Grail", 1975, "Terry Gilliam, Terry Jones"),
("Monty Python's Life Of Brian", 1979, "Terry Jones"),
("Monty Python Live At The Hollywood Bowl", 1982, "Terry Hughes"),
("Monty Python's The Meaning Of Life", 1983, "Terry Jones")
]
writer = csv.writer(open("test.csv"), delimiter=",")
writer.writerows(data)
CSV Output:
And Now For Something Completely Different,1971,Ian MacNaughton
Monty Python And The Holy Grail,1975,"Terry Gilliam, Terry Jones"
Monty Python's Life Of Brian,1979,Terry Jones
Monty Python Live At The Hollywood Bowl,1982,Terry Hughes
Monty Python's The Meaning Of Life,1983,Terry Jones
More examples can be found on http://docs.python.org/dev/lib/csv-examples.html (Python Documentation Pages)