Created
April 29, 2020 10:18
-
-
Save thomhayward/0ae131408a614688665324a7ee3b3008 to your computer and use it in GitHub Desktop.
Concatenate track segments of multiple .gpx files into one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
## | |
## Concatenate track segments of multiple .gpx files into one. | |
## | |
## Usage: python concatgpx.py [input1] [input2] [...] > [output] | |
## | |
## If the first .gpx file contains more than one <trkseg>, then the output file will contain a <trk> element | |
## with multiple <trkseg> child elements appended from the subsequent input files. If there is only a single | |
## <trkseg> element in the first input file, then the output file will contain a <trk> element with a single | |
## <trkseg> element containing all the <trkpt> elements from the subsequent input files. | |
## | |
import sys | |
import xml.etree.ElementTree as ElementTree | |
ns = { 'gpx': 'http://www.topografix.com/GPX/1/1' } | |
ElementTree.register_namespace('', ns['gpx']) | |
output = None | |
append_segments = False | |
for source in sys.argv[1:]: | |
tree = ElementTree.parse(source) | |
if output is None: | |
output = tree | |
append_segments = len(tree.findall('./gpx:trk/gpx:trkseg', ns)) > 1 | |
continue | |
if append_segments: | |
root = output.find('./gpx:trk', ns) | |
map(root.append, tree.findall('./gpx:trk/gpx:trkseg', ns)) | |
else: | |
root = output.find('./gpx:trk/gpx:trkseg', ns) | |
map(root.append, tree.findall('./gpx:trk/gpx:trkseg/gpx:trkpt', ns)) | |
if output: | |
output.write(sys.stdout, encoding='utf-8', xml_declaration=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment