Last active
January 27, 2021 22:05
-
-
Save willjobs/8146866bfe10fcd7942bede1cb160716 to your computer and use it in GitHub Desktop.
Merge (and possibly rename) GPX files
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
######## | |
# This code is useful for combining many GPX files, each with a single <trk>, into | |
# a single GPX file containing one <trk> that has one <trkseg> per input GPX file. | |
# | |
# This is necessary for animating GPX files using GPX Animator: https://gpx-animator.app/ | |
######## | |
import shutil | |
import glob | |
from datetime import datetime | |
import gpxpy | |
import gpxpy.gpx | |
files = glob.glob('runs/*.gpx') | |
######## | |
# If you also want to renaming a series of .gpx files based on the | |
# name of the first (possibly *only*) track in the gpx file, uncomment this. | |
# It assumes the date format is like this: '2019-06-02T13:32:41.175Z'. | |
######## | |
# output_dir = 'revised' | |
# | |
# for f in files: | |
# with open(f, 'r') as gpx_file: | |
# gpx = gpxpy.parse(gpx_file) | |
# datestr = gpx.tracks[0].name[4:-5] | |
# new_name = datetime.strptime(datestr, '%Y-%m-%dT%H:%M:%S').strftime('%Y%m%d-%H%M%S') | |
# shutil.copyfile(f, f'{output_dir}/{new_name}.gpx') | |
# print(f'old: {f} --> new: {output_dir}/{new_name}.gpx') | |
# create new GPX file, append a blank track | |
new_gpx = gpxpy.gpx.GPX() | |
new_track = gpxpy.gpx.GPXTrack() | |
new_gpx.tracks.append(new_track) | |
for f in files: | |
with open(f, 'r') as gpx_file: | |
gpx = gpxpy.parse(gpx_file) | |
new_track.segments.append(gpx.tracks[0].segments[0]) | |
with open('merged_runs.gpx', 'w') as f: | |
f.write(new_gpx.to_xml()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment