Search code examples
pythoncan-bus

Split blf-files in Python into smaller files


I'm wondering if it is possible to split BLF-files in Python? I know that there is a library (can) that supports BLF-files, but find no documentation on how to split/save. I can read a BLF-file with:

 import can
 log = can.BLFReader("logfile.blf")

Would appreciate any help if anybody has knowledge in how I would split this file, and save it into smaller blf-files.


Solution

  • You can read your logfile and write all messages to new files, changing file every N messages (in my example N=100, which is very low). I find it very useful to look at the doc, otherwise I wouldn't know how to resume iteration over log_in (in this case as a generator) or how to easily get object_count:

    import can
    
    OUTPUT_MAX_SIZE = 100
    
    with open("blf_file.blf", 'rb') as f_in:
        log_in = can.io.BLFReader(f_in)
        log_in_iter = log_in.__iter__()
        object_count = log_in.object_count
        i = 0
        while i*OUTPUT_MAX_SIZE < object_count:
            i += 1
            with open(f"smaller_file{i}.blf", 'wb') as f_out:
                log_out = can.io.BLFWriter(f_out)
                j = 0
                while j < OUTPUT_MAX_SIZE:
                    log_out.on_message_received(log_in_iter.__next__())
                    j += 1
                log_out.stop()