[Tutor] Perl to Python code migration

Sean 'Shaleh' Perry shalehperry@attbi.com
Thu, 5 Sep 2002 12:41:38 -0700


On Thursday 05 September 2002 11:01, Jeff Shannon wrote:
> Levy Lazarre wrote:
> > Good afternoon all,
> >
> > In Python what is the fastest way to break a file into
> > records according to a fixed string delimiter? [...]
> >
> > The string "(ID   1)" marks the beginning of a new
> > record. [...]
>
> Try using the split() string method.
>
> infile =3D open('myfile.txt', 'r')
> data =3D infile.read()
> infile.close()
> records =3D data.split( "(ID 1)" )
>
> Now 'records' holds a list.  Each element of that list is a block that =
was
> delimited by the argument to split() (in this case, "(ID 1)").  Note th=
at
> if your file starts with the delimiter, then records[0] will be an empt=
y
> string.
>

and you just violated his request that the whole file not be read in at o=
nce.

I am not aware of a clean method that mimics the perl code directly.  My =
usual=20
tactic is to read the file line by line looking for the tags I am interes=
ted=20
in (like 'ID 1') and use something like a state variable to control furth=
er=20
reading.