Advertisement
Uno-Dan

Untitled

Dec 15th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. ########################################################################################################################
  2. #    File: main.py
  3. #  Author: Dan Huckson, https://github.com/unodan
  4. #    Date: 2018-12-15
  5. ########################################################################################################################
  6.  
  7. import csv
  8. import os
  9. import json
  10.  
  11. subdivision = '2018-1 SubdivisionCodes.csv'
  12.  
  13. cities = []
  14. countries = []
  15.  
  16. COUNTRIES = ['CA', 'US']
  17. encoding = 'ISO 8859-1'
  18.  
  19. files = []
  20. for file in os.listdir('.'):
  21.     if 'UNLOCODE' in file:
  22.         files.append(file)
  23. files = sorted(files)
  24.  
  25. with open(subdivision, encoding=encoding) as f:
  26.     reader = csv.reader(f, delimiter=',', quotechar='"')
  27.  
  28.     for row in reader:
  29.         country_code, zone_code, zone_name, zone_type = row
  30.         if country_code in COUNTRIES:
  31.             countries.append({
  32.                 'country_code': country_code,
  33.                 'zone_code': zone_code,
  34.                 'zone_name': zone_name,
  35.                 'zone_type': zone_type,
  36.             })
  37.  
  38.     for country in countries:
  39.         file = None
  40.         found = False
  41.         for file in files:
  42.             with open(file, encoding=encoding) as g:
  43.                 data = g.readlines()
  44.  
  45.             end_country_code = data[-1].split(',')[1].strip('"')
  46.             if country['country_code'] <= end_country_code:
  47.                 found = True
  48.                 break
  49.  
  50.         with open(file, encoding=encoding) as g:
  51.             reader = csv.reader(g, delimiter=',', quotechar='"')
  52.  
  53.             for row in reader:
  54.                 if country['country_code'] == row[1]:
  55.                     country_code = row[1]
  56.                     city = row[3]
  57.                     zone_code = row[5]
  58.                     if country_code in COUNTRIES:
  59.                         cities.append({
  60.                             'country_code': country_code,
  61.                             'zone_code': zone_code,
  62.                             'zone_type': country['zone_type'],
  63.                             'city': city,
  64.  
  65.                         })
  66.  
  67.     with open('out.json', 'w') as x:
  68.         json.dump(cities, x, indent=4)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement