Last active
May 13, 2018 12:46
-
-
Save TimSC/9593381df476d712f53e75741a4066ce to your computer and use it in GitHub Desktop.
OS Codepoint file reader, Released under the CC0 license.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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