[PYTHON] Read and Write CSV files
Python
Www.python.org, version 2.4 supports the
de facto CSV format (comma-separated values: Comma Separated Values).
The Reference Library is very explanatory in this regard, but only in English.
Here is how to read and write CSV with Python.
Prerequisite
Nothing really impossible:
-> Knowledge of Python
-> Python 2.4 Distribution
Writing a CSV file
Let's start by importing the CSV module:
import csv
We will define an object "writer" (named c), which can later be used to write the CSV file.
c = csv.writer(open("MYFILE.csv", "wb"))
Now we will apply the method to write a writerow row. Writerow The method takes one argument: this argument must be a list and each list item is equivalent to a column. Here, we try to make an address book.
c.writerow(["Name","Address","Telephone","Fax","E-mail","Others"])
Then we will save all entries in this way.
Reading a CSV file
First just create and objectnreader (we will give it a name: cr).
cr = csv.reader(open("MYFILE.csv","rb"))
And here we get each row (in the form of a list of columns) as follows:
for row in cr:
print row
We can of course extract a precise entry of a row with the index (as a list but a list).
for row in reader:
print row[2], row[-2]