Minimal example how to read .osm.pbf file using Python & osmium

This minimal example uses the osmium python binding to read an .osm.pbf file and count the number of nodes, ways and relations.

First, we need to download a suitable dataset. For this example, we’ll be using kenya-latest.osm.pbf which you can download from Geofabrik:


Now we can run the script:

#!/usr/bin/env python3
import osmium as osm

class OSMHandler(osm.SimpleHandler):
    def __init__(self):
        self.node_count = 0
        self.way_count = 0
        self.relation_count = 0

    def node(self, n):
        self.node_count += 1

    def way(self, w):
        self.way_count += 1

    def relation(self, r):
        self.relation_count += 1

osmhandler = OSMHandler()
print(f'Number of nodes: {osmhandler.node_count}')
print(f'Number of way: {osmhandler.way_count}')
print(f'Number of relations: {osmhandler.relation_count}')

Example output:

Number of nodes: 29442019
Number of way: 3188550
Number of relations: 2225