[Tutor] Newbie text file processing question

Sean 'Shaleh' Perry shalehperry@attbi.com
Tue, 07 May 2002 09:48:29 -0700 (PDT)


> 
> 
> I want to do conditional stuff based around if the line is lineA or lineB.
> 
> For example if a line in foo.txt equals "lineA", then check that
> lineA1stuff equals eggs and lineABstuff equals spam.  If a line equals
> "lineB", then check that lineB1stuff equals cars and lineABstuff equals
> trucks, etc.  NOTICE that the contents of line, "lineABstuff", should be
> different if it follows line A or line B.  (I hope this isn't too confusing
> !)
> 
> I can more-or-less do what I want using line by line processing and if
> statements, but the lines, "lineA" and "lineB" aren't being used for
> conditional checking and actions (only the "*stuff" lines are).  Is there a
> better way to do this ?
> 

there are two approaches I often use.  1) state checking and 2) function
handlers.

WANT_A = 1
WANT_B = 2

if line == lineA: state = WANT_A
if line == lineB: state = WANT_B
if state == WANT_A:
  if line is not A type:
    complain
elif state == WANT_B:
  if line is not B type:
    complain

or perhaps (second option):

if line == lineA:
  read_a_data(file)
elif line == lineB:
  read_b_data(file)

the two functions would read lines from the file until they hit something they
did not understand.