python-fitparse Documentation

repository·master·Indexed 21 days ago

https://github.com/dtcooper/python-fitparse

A Python library for parsing Garmin .FIT files to access sensor data, GPS coordinates, and telemetry. It provides the FitFile class for reading files, file-like objects, or raw bytes, and the DataMessage class for extracting record values and metadata. Requires Python 3.6 or above.

Tokens
1.5K
Snippets
6
Records
9
Agent score
24%

What's inside python-fitparse

  1. Handle FitParseError during parsing

    master

    Operations that parse the underlying FIT data (like accessing messages or calling parse()) may raise a FitParseError if invalid data is encountered.

    To catch errors early, it is recommended to call fitfile.parse() immediately after creating the FitFile object.

    import sys
    from fitparse import FitFile, FitParseError
    
    try:
        fitfile = FitFile('/path.to/fitfile.fit')
        fitfile.parse()
    except FitParseError as e:
        print "Error while parsing .FIT file: %s" % e
        sys.exit(1)
  2. Print all record fields in a FIT file

    master

    You can use the FitFile class to parse a .fit file and iterate through its messages. To extract specific data, use get_messages('record') to retrieve all messages of type 'record', then iterate through the entries in each record to access their name, value, and units.

    from fitparse import FitFile
    
    fitfile = FitFile('/home/dave/garmin-activities/2012-12-19-16-14-54.fit')
    
    # Get all data messages that are of type record
    for record in fitfile.get_messages('record'):
    
        # Go through all the data entries in this record
        for record_data in record:
    
            # Print the records name and value (and units if it has any)
            if record_data.units:
                print(" * %s: %s %s" % (
                    record_data.name, record_data.value, record_data.units,
                ))
            else:
                print(" * %s: %s" % (record_data.name, record_data.value))
        print()
  3. Initialize the FitFile object

    master

    The FitFile class is the primary interface for reading .FIT files. You can initialize it using a file path, a file-like object, or a raw string of bytes.

    Supported input types for the fileish parameter:

    • File path: A string representing the path to the .FIT file.
    • File-like object: An open file object (e.g., from open(path, 'rb')).
    • Raw bytes: A string of bytes containing the FIT data.

    Optional parameters:

    • check_crc (bool): Set to False to disable CRC validation.
    • data_processor: An alternate data processor object (defaults to FitFileDataProcessor).
    # Specifying a file path
    fitfile = FitFile('/path.to/fitfile.fit')
    
    # Providing a file-like object
    file_obj = open('/path.to/fitfile.fit', 'rb')
    fitfile = FitFile(file_obj)
    
    # Providing a raw string of bytes
    file_obj = open('/path.to/fitfile.fit', 'rb')
    raw_fit_data = file_obj.read()
    fitfile = FitFile(raw_fit_data)
  4. Inspect DataMessage metadata

    master

    Each DataMessage object contains metadata about the record:

    • name: The name of the DataMessage as defined by its definition message.
    • mesg_num: The message number.
    • mesg_type: The associated MessageType. This may be None if no associated message type is defined in the SDK profile.
  5. Access FIT messages via FitFile

    master

    You can retrieve the data records contained in a .FIT file using the following methods on a FitFile instance:

    • messages: A convenience attribute that returns a list of DataMessage objects. This is functionally equivalent to calling list(self.get_messages()).
    • get_messages(name=None, with_definitions=False, as_dict=False): A method to iterate through the messages in the file.
  6. Read data from DataMessage objects

    master

    A DataMessage represents a single record in the FIT file. These are obtained via FitFile.messages or FitFile.get_messages().

    To extract information from a DataMessage:

    • get_values(): Returns a dict mapping field names to their values.
    • get_value(field_name): Returns the value for a specific field, or None if it doesn't exist.
    • get(field_name, as_dict=False): Returns a FieldData object for the specified field, or a dict representation if as_dict=True.
    # Example of getting all values from a message
    data_message.get_values()
    {
        'altitude': 24.6,
        'cadence': 97,
        'distance': 81.97,
        'grade': None,
        'heart_rate': 153,
        'position_lat': None,
        'position_long': None,
        'power': None,
        'resistance': None,
        'speed': 7.792,
        'temperature': 20,
        'time_from_course': None,
        'timestamp': datetime.datetime(2011, 11, 6, 13, 41, 50)
    }