Skip to content

Instantly share code, notes, and snippets.

@TimSC
Last active May 13, 2018 12:46
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 TimSC/9593381df476d712f53e75741a4066ce to your computer and use it in GitHub Desktop.
Save TimSC/9593381df476d712f53e75741a4066ce to your computer and use it in GitHub Desktop.
OS Codepoint file reader, Released under the CC0 license.
#OS Codepoint file reader, by Tim Sheerman-Chase 2018
#Released under the CC0 license.
import zipfile
import csv
import os
import io
#Get Code point open from https://www.ordnancesurvey.co.uk/business-and-government/products/code-point-open.html
def ReadCodePoint(fi, callback):
for info in fi.infolist():
pathSp = os.path.split(info.filename)
if pathSp[0] != "Data/CSV":
continue
rawFile = io.StringIO(fi.read(info.filename).decode('utf-8'))
fileData = csv.reader(rawFile, lineterminator="\n")
for li in fileData:
callback(li)
class CodePointMemStore(object):
def __init__(self):
self.postcodes = {}
def __call__(self, val):
po1, po2 = val[0][:4].strip(), val[0][4:]
self.postcodes[(po1, po2)] = list(map(int, val[2:4]))
def UpdatePostcodeList(fina, memStore, outFina):
#Takes a list of postcodes and appends eastings and northings
fi = csv.reader(open(fina, "rt"))
fiout = csv.writer(open(outFina, "wt"))
for li in fi:
po1, po2 = li[0][:4].strip().upper(), li[0][4:].strip().upper()
eastnorth = memStore.postcodes[(po1, po2)]
print (po1, po2, eastnorth)
fiout.writerow(li+eastnorth)
del fi
del fiout
if __name__=="__main__":
data = zipfile.ZipFile('codepo_gb.zip')
memStore = CodePointMemStore()
ReadCodePoint(data, memStore)
UpdatePostcodeList('mempostcodes.txt', memStore, 'mempostcodes2.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment