Skip to content

Instantly share code, notes, and snippets.

@cedricbonhomme
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cedricbonhomme/fc6a792f25183867e955 to your computer and use it in GitHub Desktop.
Save cedricbonhomme/fc6a792f25183867e955 to your computer and use it in GitHub Desktop.
French postal codes
#! /usr/bin/env python
#-*- coding: utf-8 -*-
import sys
import csv
import urllib2
from contextlib import contextmanager
POSTAL_CODES = "https://www.data.gouv.fr/s/resources/base-officielle-des-codes-postaux/20141106-120608/code_postaux_v201410.csv"
@contextmanager
def open_url(url):
try:
f = urllib2.urlopen(url)
except IOError as err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
def usage():
print "This script takes one argument."
print "Usage:"
print "\tpcodes.py city"
exit(1)
if __name__ == "__main__":
# Point of entry in execution mode.
if len(sys.argv) != 2:
usage()
city = sys.argv[1]
with open_url(POSTAL_CODES) as (postal_codes, err):
if err:
print err
else:
dialect = csv.Sniffer().sniff(postal_codes.read(1024))
rows = csv.reader(postal_codes, dialect)
result = sorted([(row[1], row[2]) for row in rows
if city.lower() in row[1].lower()],
key=lambda x: x[0])
print "\n".join([value + " " + key for key, value in result])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment