Friday, June 8, 2018

Unable to parse KML file in python 3 with PyKML module


Recently, I picked up a project where I had to read/parse in a point KML file and do reverse geocoding on the latitudes and longitudes coordinates of the points. So, I found a nice python module that will help me accomplish this. But I found out that it doesn't work fine on python 3 installation but works great on python 2.

When I import pyKML as follow "from pykml import parser" in python3, it returns the error as thus: ModuleNotFoundError: No module named 'urllib2'

I knew the pyKML module was trying to work with 'urllib2' module which has changed in python3. Since python2 will soon be discontinued, I have to find a solution for it to work on python3.

Ok, just in case you don't know pyKML, according to the documentation, pyKML is a Python package for creating, parsing, manipulating, and validating KML documents/files. A KML is language for encoding and annotating geographic data used by Google Earth, Google Maps and a number of other GIS platforms.


Here is how I got it working on python3....

To solve it, you need to fix "urllib2" to work well in python3 by editing the pyKML "" file. This file was installed when you installed pyKML, so locate it wherever, it was installed.

In most cases, it will in you python3 'dist-packages' folder at: C:\...\Lib\site-packages\pykml\

Change this line "import urllib2" to
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

Save the file and reload the import statement, there won't be any error.

That is it.

1 comment:

  1. Had the exact same problem and this solved it, couldn't believe my luck. Thanks so much