Next / Previous / Contents / Shipman's homepage

6. scanFieldList(): A utility routine for flat-file scanning

This function is used when we need to disassemble a record from a flat file. It takes two arguments:

baseclasses.py
# - - -   s c a n F i e l d L i s t   - - -

def scanFieldList(scan, fieldList):
    '''Take apart a record from a flat file.

      [ (scan is a Scan object containing a flat file record) and
        (fieldList is a list of 2-tuples (name, length)
        describing the fields in that record) ->
          if the line in scan starts with the fields described by
          fieldList ->
            scan  :=  scan advanced past those fields
            return a list of those fields
          else ->
            Log()  +:=  error message describing the name and
                expected length of the first missing field
            raise IOError ]
    '''

The outer loop iterates over the fields in fieldList.

baseclasses.py
    #-- 1 --
    result = []

    #-- 2 --
    for  (fieldName, fieldSize) in fieldList:
        #-- 2 body --
        # [ if scan starts with (fieldSize) characters ->
        #     scan  :=  scan advanced by fieldSize
        #     result  :=  result + (next fieldSize characters
        #                 from scan)
        #   else ->
        #     Log()  +:=  (error message describing name (fieldName)
        #                 and size (fieldSize))
        #     raise IOError ]

        #-- 2.1 --
        # [ if scan starts with fieldSize characters ->
        #     scan   :=  scan advanced by fieldSize
        #     field  :=  next fieldSize characters from scan
        #   else -> raise IOError ]
        try:
            field = scan.move(fieldSize)
        except IndexError:
            raise IOError("Expecting a %s field of length %d." %
                             (fieldName, fieldSize))

        #-- 2.2 --
        result.append(field)

    #-- 3 --
    return result