[Tutor] Newbie text file processing question

Andrei Kulakov ak@silmarill.org
Tue, 7 May 2002 14:02:15 -0400


On Tue, May 07, 2002 at 12:35:36PM -0400, stuart_clemons@us.ibm.com wrote:
> 
> Hi all:
> 
> I have a question about conditional branching based on the contents of a
> text file.  I'll try my best to make this understandable !
> 
> My file is:  foo.txt
> 
> The contents of foo.txt are:
> 
>       (1)lineA
>       (2)   lineA1stuff=eggs
>       (3)   lineABstuff=spam
>       (4)lineB
>       (5)   lineB1stuff=cars
>       (6)   lineABstuff=trucks
>       (7)   lineB2stuff=books
>       (8)lineA
>       (9)   lineA1stuff=eggs
>       (10   lineA2stuff=eggs
> 
> 
> 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 ?
> 
> Here's an example of the code construct I was thinking of using.
> 
>       infile = open('f:\\Python22\\foo.txt', 'r')
>       for line in infile.xreadlines():
>             if line[3:8] == "lineA":
>                   print "Yes, this is line A", line
>             if line[7:18] == "lineA1stuff":
>                   if line[19:23]== "eggs":
>                         print "this is correct"
>                   else:
>                         print "this is incorrect"
>             if line[3:8] == "lineB": , etc, etc, etc
>
This is no good because it relies on exact positions - this can easily
break.

if line.strip() == "lineA":
    print "This is line A"
elif line.strip() == "lineB":
    print "Line B here"
else:
    var, val = line.split('=')
    var = var.strip()
    val = val.strip()
    if var == "lineA1stuff":
        if val == "eggs":
            print "Line A1 is eggs"

- Andrei

> 
> Sorry if this is hopelessly incoherent.
> 
> - Stuart
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org