How to fix thiss error when taking a sample of OpenStreetMap data?

I am trying to take a sample of the OSM file but keep getting stuck with the following error

I have this piece of code below and I keep receiving the following error:

ERROR:

File "<ipython-input-31-e45dfe148a3d>", line 31
output.write({'</osm>'})
^
SyntaxError: invalid syntax

CODE:

import xml.etree.ElementTree as ET  # Use cElementTree or lxml if too slow
import os

OSM_FILE = os.path.join("/Users/projects/sandiego.osm")  

SAMPLE_FILE = "sample.osm"


def get_element(osm_file, tags=('node', 'way', 'relation')):
    """Yield element if it is the right type of tag
    Reference:
    [http://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python](http://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python)
    """
    context = ET.iterparse(osm_file, events=('start', 'end'))
    _, root = next(context)
    for event, elem in context:
        if event == 'end' and elem.tag in tags:
            yield elem
            root.clear()


with open(SAMPLE_FILE, 'wb') as output:
    output.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    output.write('<osm>\n  ')

    # Write every 10th top level element
    for i, element in enumerate(get_element(OSM_FILE)):
        if i % 50 == 0:
            output.write(str(ET.tostring(element, encoding='UTF-8'))

    output.write('</osm>')

exonlinecalculator

I’d suggest using an OSM specific library rather than a generic XML one. PyOsmium would be an appropriate choice.

A simpler approach would be to use Osmium Tool to convert the OSM to a CSV format & just use regular UNIX tools to sample every 10th row.