[Tutor] Omitting lines matching a list of strings from a file

Alan Gauld alan.gauld at btinternet.com
Thu Feb 25 10:24:31 CET 2010


<galaxywatcher at gmail.com> wrote 

>I am trying to output a list of addresses that do not match a list of  
> State abbreviations. What I have so far is:
> 
> def main():
>     infile = open("list.txt", "r")
>     for line in infile:
>         state = line[146:148]
>         omit_states = ['KS', 'KY', 'MA', 'ND', 'NE', 'NJ', 'PR',  
> 'RI', 'SD', 'VI', 'VT', 'WI']
>         for n in omit_states:
>             if state != n:
>                 print line

This prints it for every entry in omit_states. 
You probably want to add a break command after the print


But I would do this with a list comprehension or generator 
expression (depending on your Python version):


lines = [line for line in infile if line[146:148] not in omit_states]
print '\n'.join(lines)

HTH,


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



More information about the Tutor mailing list