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

Alan Gauld alan.gauld at btinternet.com
Sun Jan 9 15:07:39 CET 2011


"tee chwee liong" <tcl76 at hotmail.com> wrote

> i got syntax error when running this line:
> data = for line in open(filename) if not line.startswith("#")

Should be:

data = [ line for line in open(filename) if not line.startswith("#") ]

Notice the extra line at the beginning and the fact that it is
surrounded by [] which makes it a *list comprehension*.


But that won't help if you can't put commment markers
at the front... But you might get away with:

data = [ line for line in open(filename) if '-1' in line ]

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list