Instantly share code, notes, and snippets.

Embed
What would you like to do?
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:
output_segment.points.append(point)
if len(output_segment.points) >= max_segment_points:
write_gpx(dest_dir, output_count, output_segment)
output_count += 1
output_segment = gpxpy.gpx.GPXTrackSegment()
output_segment.points.append(point)
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()
gpx.tracks.append(gpx_track)
gpx_track.segments.append(segment)
with open(os.path.join(dest_dir, str(i) + ".gpx"), "wb") as f:
f.write(gpx.to_xml())
def _main():
usage = "usage: %prog"
parser = OptionParser(usage=usage,
description="")
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__":
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment