python et CSV

Il existe en standart dans un python un module cvs qui permet de gérer les fichiers cvs

lecture d’un fichier

import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
    print row

ou

import csv
reader = csv.reader(open("some.csv", "rb"))
for title, year, director in reader:
    print year, title

utilisation d’un autre format

import csv
reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
for row in reader:
    print row

écriture d’un fichier cvs

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(sys.stdout)

for item in data:
    writer.writerow(item)
# ou writer.writerows(data)

ou

import csv
c = csv.writer(open("MONFICHIER.csv", "wb"))
c.writerow(["Nom","Adresse","Telephone","Fax","Courriel","Autres"])

code qui permet de créer à partir d’une fichier csv une liste de dictionnaire d’objet

import csv
def read_csv(file_csv):
    data = []
    objs = []
    reader = csv.reader(open(file_csv, "rb"), delimiter=';')
    for row in reader:
        data.append(row)
    for i in data[1:]:
        obj = {}
        for j in range(0, len(data[0])):
            obj[data[0][j]] = i[j]
        objs.append(obj)
    return objs