"""
# Manipulate KML file
"""
"""
On this notebook I'll show how to parse and manipulte the kml file in order to generate a csv file with the relevant information.
I'll use the Medellin, Colombia postal codes kml file obtained from the medata.gov.co site.
"""
"""
First setup the enviroment
"""
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

#import numpy as np # linear algebra
#import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
"""
This code will load pykml parser, parse the XML on pyxml, and write csv file with relevant information.
"""
!pip install pykml
from pykml import parser
fcsv = "./postalcodes.csv"
fp = "../input/medellin-colombia-postal-codes-with-polygons/Codigo_Postal.kml"
fcsvfd = open(fcsv,"w")
with open(fp, 'r') as f:
    root = parser.parse(f).getroot()
for el in root.Document.Folder.Placemark:
    placemark = ""
    for sd in el.ExtendedData.SchemaData.SimpleData:
        placemark += str(sd) + "\t"
    placemark+=el.Polygon.outerBoundaryIs.LinearRing.coordinates+"\n"
    fcsvfd.write(placemark)
fcsvfd.close()

