Unix fold command in python

Larry Bates lbates at swamisoft.com
Mon Jun 14 16:03:55 CEST 2004


Something like this works for me (not tested).

I'll of course this will just return the character
values of the fields.  I'll leave the conversion
to int's, float's or any other value types you
many need to you.  If any of the bytes contain
binary data, you will need the struct module to
decode them.

Larry Bates
Syscon, Inc.


class record:
    def __init__(self, data=None):
        #
        # User can either pass the data at class
        # creation or later by calling parse.
        #
        self._fields=(('field1',  0,  4),
                      ('field2',  5,  8),
                      ...
                      ('fieldn',238,242))

    if data is not None: self._parse(data)
    return

    def parse(self, data):
        D=self.__dict__
        for fieldname, begin, end in self._fields:
            D[fieldname]=data[begin, end+1]

        return

if __name__=="__main__":

    #
    # Open file and read all lines, if this is a huge
    # file you will need to do this differently by using
    # xreadlines inside the loop below.
    #
    fp=open(inputfile, 'r')
    lines=fp.readlines()
    fp.close()
    #
    # Create an instance of your record class
    #
    RECORD=record()

    for line in lines:
        RECORD.parse(line)
        print RECORD.field1
        print RECORD.field2
        ...
        print RECORD.fieldn


"dean" <diabolik at uku.co.uk> wrote in message
news:70efe2ee.0406140250.79dc95b8 at posting.google.com...
> Hello Group:
>
> Hopefully someone can answer my question.
>
> I have a unix shell command that I would like to emulate in python. I
> am sanning a file that contains a stream of data with a record size of
> 242 bytes but no record delimiters. There are multiple fields in each
> record that can be mapped according to their position:
>
> example
>
> field1 byte 0-4
> field2 byte 5-8
> ...
> ...
> ...
fieldn byte 238-242
>
> How do I make python read a record in and report the contents of a
> particular field (and may be carry out an operations with that field).
>
> Much appreciated
>
> regards
>
> dean





More information about the Python-list mailing list