This function takes two arguments: a DbfFieldDef object defining a field, and an
object representing the field's value. Its purpose is to
convert the value to a string (if it isn't one already)
and pad it to the length from the field definition.
# - - - f l a t t e n F i e l d - - -
def flattenField(fieldDef, value):
'''Flatten one field.
[ (fieldDef is the definition of a field as a DbfFieldDef) and
(value is the value of one such field) ->
return value, converted to a string, and padded to
the length defined in fieldDef.length ]
'''
Life would be simpler here if the dbfpy package
gave us the field value as stored in the file, which is
always a string and always the full length. However,
because the package has been nice enough to convert it to
one of the standard Python types, we have to convert it
back to a string.
We can't pad all values the same way, either. Numbers
should be right-justified, and strings should be
left-justified. We use Python's built-in isinstance function to determine whether the
value is one of the numeric types. The isinstance() function takes two arguments. The
first argument is the object to be tested. The second
argument can be either a class or a sequence of classes.
It returns a True value if the object is a
member of any of the classes, or derived from them.
#-- 1 --
# [ if value is an instance of int, long, or float class ->
# result := value, as a string, right-justified to
# length fieldDef.length
# else ->
# result := value, as a string, leftt-justified to
# length fieldDef.length ]
if isinstance(value, (int, long, float)):
result = str(value).rjust(fieldDef.length)
else:
result = str(value).ljust(fieldDef.length)
#-- 2 --
return result