Search code examples
pythonpython-3.xxlrd

How to read excel file in python and rewrite it?


I have an Excel sheet full of addresses and base on these addresses (the postal code), determine whether they belong to North/South/East/West region.

An example of how an address looks:

164 Penang Road, 01-05, 238464

238463 being the postal code, and how North/South/East/West region is determined is base on the first 2 numbers '23'.

This is my current code:

import xlrd

loc = ("C:\\Users\Desktop\Windflower\\address.xlsx")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)

for i in range(sheet.nrows):
   print(sheet.cell_value(i, 0))

How do I go about coding a program which reads only the first 2 numbers of the postal code and determines which region it belongs to?

So my output would be placed into a new excel sheet:

I just started coding and I've read that you can do an if/else method but so far I'm getting errors.


Solution

  • Following your codestyle you can try this

    for i in range(sheet.nrows):
        address = sheet.cell_value(i,0)
        address = address.rstrip() #to remove trailing spaces if any
        zip = address[-6:-4]  #to get the first two digits of zip