input record seperator (equivalent of "$|" of perl)

Fredrik Lundh fredrik at pythonware.com
Sun Dec 19 16:46:51 EST 2004


les_ander at yahoo.com wrote:

> I know that i can do readline() from a file object.
> However, how can I read till a specific seperator?
>
> for exmple,
> if my files are
>
> name
> profession
> id
> #
> name2
> profession3
> id2
>
> I would like to read this file as a record.
> I can do this in perl by defining a record seperator;
> is there an equivalent in python?

not really; you have to do it manually.

if the file isn't too large, consider reading all of it, and splitting on the
separator:

    for record in file.read().split(separator):
        print record # process record

if you're using a line-oriented separator, like in your example, tools like
itertools.groupby can be quite handy:

    from itertools import groupby

    def is_separator(line):
         return line[:1] == "#"

    for sep, record in groupby(file, is_separator):
         if not sep:
              print list(record) # process record

or you could just spell things out:

    record = []
    for line in file:
         if line[0] == "#":
              if record:
               print record # process record
               record =  []
     else:
          record.append(line)
    if record:
        print record # process the last record, if any

</F> 






More information about the Python-list mailing list