[Tutor] Open a text file, read and print pattern matching

Corey Richardson kb1pkl at aim.com
Sun Jan 9 07:41:43 CET 2011


On 01/09/2011 01:25 AM, tee chwee liong wrote:
> hi,
> 
> i have a sampledata as below. Pls refer to output, if found -1, how to
> list out all the Lane number? And if there is no -1, print PASS. My code
> is as below section.
>  
> thanks
> tcl76
>  
> ####sampledata############
> Platform: PC
> Tempt : 25
> TAP0 :0
> TAP1 :1
> 
> +++++++++++++++++++++++++++++++++++++++++++++
> Port Chnl Lane EyVt
> +++++++++++++++++++++++++++++++++++++++++++++
> 0       1      1    75
> 0       1      2    -1
> 0       1      3    10
> 0       1      4    -1
> 0       1      5    12
> +++++++++++++++++++++++++++++++++++++++++++++
> Time: 20s
> ############################
>  
> ####output###################
> case1: Found -1
> Lane 2 FAIL
> Lane 4 FAIL
>  
> case2: No -1
> All Lanes PASS
> ##########################
You couldn't possibly have gotten that output from the code you
provided, so why did you list it under output?
>  
> ####Code####################
> fname = "sampledata.txt"
> pattern = "-1"
> for search in open(fname):
>     if pattern in search:
>         print "FAIL"
>     else:
>         print "PASS"
> 
>  
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

I'm not quite sure how your data file is supposed to be laid out. I
suggest you have it setup so that every line that isn't actually data is
commented out somehow, and you only search the actual data. So, your new
data file could look like:

-------paste----------------------------------
#Platform: PC
#Tempt : 25
#TAP0 :0
#TAP1 :1

#+++++++++++++++++++++++++++++++++++++++++++++
#Port Chnl Lane EyVt
#+++++++++++++++++++++++++++++++++++++++++++++
0       1      1    75
0       1      2    -1
0       1      3    10
0       1      4    -1
0       1      5    12
#+++++++++++++++++++++++++++++++++++++++++++++
#Time: 20s
---------end-paste----------------------------

Your script could look something like:

data = [for line in open(filename) if not line.startswith("#")
for line in data:
    line = line.split()
    if line[3] == pattern:
        print "Lane " + line[2] + " PASS"
    else:
        print "Lane " + line[2] + " FAIL"

~Corey Richardson


More information about the Tutor mailing list