Create a gist now

Instantly share code, notes, and snippets.

Split a gpx file into multiple files
#!/usr/bin/env python
import logging
from optparse import OptionParser
import os
import gpxpy
import gpxpy.gpx
def split_gpx(source, dest_dir, max_segment_points=500):
logging.debug("Splitting file " + source + " into files in " + dest_dir)
output_count = 1
with open(source, "rb") as f:
gpx = gpxpy.parse(f)
output_segment = gpxpy.gpx.GPXTrackSegment()
for track in gpx.tracks:
for segment in track.segments:
for point in segment.points:
if len(output_segment.points) >= max_segment_points:
write_gpx(dest_dir, output_count, output_segment)
output_count += 1
output_segment = gpxpy.gpx.GPXTrackSegment()
if len(output_segment.points) > 1:
write_gpx(dest_dir, output_count, output_segment)
def write_gpx(dest_dir, i, segment):
gpx = gpxpy.gpx.GPX()
gpx_track = gpxpy.gpx.GPXTrack()
with open(os.path.join(dest_dir, str(i) + ".gpx"), "wb") as f:
def _main():
usage = "usage: %prog"
parser = OptionParser(usage=usage,
parser.add_option("-d", "--debug", action="store_true", dest="debug",
help="Turn on debug logging")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet",
help="turn off all logging")
parser.add_option("-p", "--points", type="int", dest="points", default=500,
help="max points per track")
(options, args) = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if options.debug else
(logging.ERROR if options.quiet else logging.INFO))
split_gpx(args[0], args[1], max_segment_points=options.points)
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment