[Tutor] Omitting lines matching a list of strings from a file
Christian Witts
cwitts at compuscan.co.za
Thu Feb 25 14:54:52 CET 2010
galaxywatcher at gmail.com wrote:
>> 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)
>
> That's very helpful. Thanks. One formatting detail: there is a blank
> line after each line printed, how do I ged rid of the extra blank lines?
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
lines = [line.strip() for line in infile if line[146:148] not in
omit_states]
print '\n'.join(lines)
or alternatively
lines = [line for line in infile if line[146:148] not in omit_states]
print ''.join(lines)
Just remember that doing a list comprehension like that on a large file
will drastically reduce the speed of your application as well as
introduce memory bloat.
--
Kind Regards,
Christian Witts
More information about the Tutor
mailing list