Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exercise: File reader with records

In a file we have "records" of data. Each record starts with three bytes in which we have the length of the record. Then the content.

8 ABCDEFGH 5 XYZQR

Given this source file

First line
Second record
Third row of the records
Fourth
5
END

using this code

filename = "rows.txt"
records  = "records.txt"

with open(filename) as in_fh:
    with open(records, 'w') as out_fh:
        for line in in_fh:
            line = line.rstrip("\n")
            out_fh.write("{:>3}{}".format(len(line), line))

we can create this file:

 10First line 13Second record 24Third row of the records  6Fourth  15  3END

The exercise is to create an iterator/generator that can read such a file record-by-record.