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

Dave Angel davea at ieee.org
Sun Jan 9 20:43:32 CET 2011


(Don't top-post.  You keep putting your responses out of order.)

On 01/-10/-28163 02:59 PM, tee chwee liong wrote:
>
> i modified the code to be:
> fname = "sampledata.txt"
> pattern = "-1"
> failed = False
> for line in open(fname):
>      data=line.split()
>      if len(data)==4:
>          port, channel, lane, eyvt = data
>      else:
>           if int(eyvt) == -1:
>               failed = True
>               print "Lane %s failed." % lane
>      if not failed:
>               print "All lanes pass."
>
> there is traceback error:
> Traceback (most recent call last):
>    File "C:\Python25\myscript\log\readfile9.py", line 10, in<module>
>      if int(eyvt) == -1:
> ValueError: invalid literal for int() with base 10: 'EyVt'
>
> pls help to advise. don't understand int() with base 10 mean?
>
> thanks
> tcl76
>
The int() function converts a string to an integer, using some base.  By 
default it uses base 10 (decimal), so it'll do what you'd expect to a 
string like "42" (which would return 42).

Apparently you don't have a valid string for an integer there.  For 
example, there might be a letter mixed in with the digits.

Your code doesn't make sense anyway, since at that line, eyvt might not 
even have a value.  And it certainly won't have a value from the current 
line.  You're in an 'else' clause, and only the if clause initializes 
that value.  that test for -1 needs to be inside the same if-clause as 
the "port, channel, ..." line.

I suspect the simplest way to do what you want is to have two loops. 
Loop inside the first one till you see a line that begins with "Port", 
then break out of that loop.

The second one will then only see the subsequent data, and at that 
point, all lines with four elements will have four numbers.

DaveA




More information about the Tutor mailing list