""" Codes postaux
  Recherche d'un code postal, d'une commune ou des communes d'un département            """
import csv

def nom(code):
    code=str(code)
    for commune in table:
        if commune['Code_postal']==code :
            return commune['Nom_commune']
    return None

def code(nom):
    for commune in table:
        if commune['Nom_commune']==nom :
            return commune['Code_postal']
    return None

def codes(nom):
    for commune in table:
        if commune['Nom_commune']==nom :
            print(commune['Code_postal'])

def affiche(dept):
    code_dept=str(dept)
    for commune in table:
        if commune['Code_postal'][:len(code_dept)]==code_dept :
            print(commune['Code_postal'],commune['Nom_commune'])

def enregistre(dept):
    fw=open("departement.csv",'w')
    w=csv.DictWriter(fw,['Code_postal','Nom_commune'],delimiter=";",lineterminator='\n')
    w.writeheader()# on enregistre l'entête
    code_dept=str(dept)
    for commune in table:
        if commune['Code_postal'][:len(code_dept)]==code_dept : # on enregistre les dictionnaires 
            w.writerow({'Code_postal':commune['Code_postal'],'Nom_commune':commune['Nom_commune']})
    fw.close()
    
fr=open("laposte_hexasmal.csv",'r')
table=list(csv.DictReader(fr,delimiter=';'))
#print(table[0].keys())
#print(table[29242])
#print(nom(74930))
#print(code("ST REMY LES CHEVREUSE"))
#affiche(78)
#enregistre(75)
codes("STE MARIE")
fr.close()
