Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import csv
#Extracts data from Postcodes districts file and turns it into a list of lists
def locationsGenerator():
with open('Postcode districts.csv', 'r') as csv_file: #Postcode districts from https://www.doogal.co.uk/postcodedownloads.php
csv_reader = csv.reader(csv_file)
next(csv_reader)
locations = []
for line in csv_reader:
newline = []
for entity in line:
entity = entity.lower()
newline.append(entity)
locations.append(newline)
return locations
#Extracts data from Admin areas file and turns it into a list of lists
def otherCSV():
with open('Admin areas.csv', 'r') as csv_file: #Admin areas from https://www.doogal.co.uk/postcodedownloads.php (List of countries and administative areas with population data)
csv_reader = csv.reader(csv_file)
next(csv_reader)
adminAreasList = []
for line in csv_reader:
newLine = []
for entity in line:
entity = entity.lower()
newLine.append(entity)
adminAreasList.append(newLine)
return adminAreasList
#Function to add in the area code of the region to the postcodes list
def addCode(locations, codes):
newPostcodesList = []
lastAdded = "s12000034" #The first code in the admin areas file
#Goes through each postcode. Checks each region of each postcode, and if that matches with a region in the admin areas list, it adds the corresponding area code to the postcode list
for line in locations:
for codeLine in codes:
if line[2] == codeLine[0]:
line[5] = codeLine[2]
lastAdded = line[5]
#If the postcode region does not match with a region from the admin areas list, it looks at the previously added code, assumes that is the correct code, and adds it to the postcode list
if line[5] == "":
line[5]=lastAdded
newPostcodesList.append(line)
return newPostcodesList
#Constructs lists from CSV files for the addCode function
postcodesList = locationsGenerator()
adminAreasList = otherCSV()
newPostcodesList = [["Postcode", "Town/Area", "Region", "Population", "Households", "Code"]] + addCode(postcodesList, adminAreasList) #Adds headers of collumns then updated postcode list
#Writes the new postcodes list with the correct codes to a new file to be used by the main body of code https://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file
with open('locations.csv', 'w', newline="") as f:
writer = csv.writer(f)
writer.writerows(newPostcodesList)