extract data from an .osm.pbf file within python

9.8k Views Asked by At

I've downloaded the great britain .osm.pbf file from http://download.geofabrik.de/europe.html and I want to be able to pull out all the lat and lons of every node. is this possible?

If i could get it into python format of some sort that would be great

1

There are 1 best solutions below

2
On

You can use pyosmium to parse an .osm.pbf file.

This simple example just prints the location and name of every node that has a name tag:

import osmium
import sys

class NamesHandler(osmium.SimpleHandler):
    def node(self, n):
        if 'name' in n.tags:
            print(f'{n.location}: ' + n.tags['name'])

def main(osmfile):
    NamesHandler().apply_file(osmfile)
    return 0

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python %s <osmfile>" % sys.argv[0])
        sys.exit(-1)

    exit(main(sys.argv[1]))

Of course, you'll probably want to do something more sophisticated with the data depending on your use case. Check the documentation for a basic usage tutorial and reference, and the README of the pyosmium GitHub repository for installation instructions.