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

tee chwee liong tcl76 at hotmail.com
Sun Jan 9 15:40:02 CET 2011


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
 
> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Sun, 9 Jan 2011 14:14:17 +0000
> Subject: Re: [Tutor] Open a text file, read and print pattern matching
> 
> 
> "tee chwee liong" <tcl76 at hotmail.com> wrote 
> 
> > File "C:/Python25/myscript/log/readfile9.py", line 5, in <module>
> > port, channel, lane, eyvt = line.split()
> > ValueError: need more than 2 values to unpack
> 
> So you need to ensure that you unpack when you have the right 
> number of fields:
> 
> either:
> 
> data = line.split()
> if len(data) = 4:
> port, channel, lane, eyvt = data
> else: continue
> # rest of your code here...
> 
> 
> or more pythonically:
> 
> try: 
> port, channel, lane, eyvt = line.split()
> # the rest of your code here
> except ValueError: continue
> 
> HTH,
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110109/06ee11f9/attachment-0001.html>


More information about the Tutor mailing list