Return lines in file that match string

Chris Rebert clp at rebertia.com
Tue Oct 28 14:58:06 EDT 2008


On Tue, Oct 28, 2008 at 11:37 AM, Travis Kirstine
<traviskirstine at gmail.com> wrote:
> I am new to python and could use some help with a fairly easy task.  I
> would like to return all lines in a file that have the string
> '<coordinates>' to a list.
>

from __future__ import with_statement

with open('path/to/file') as f:
    desired_lines = [line.strip() for line in f if "<coordinates>" in line]

For your reference, that uses the "with statement" and "list comprehensions".
It would also be advisable for you to read through the fine tutorial
at: http://docs.python.org/tutorial/index.html

Cheers,
Chris

> Regards,
>
> --
> Travis K.
>
> Toronto, Canada
> ------------------------------------------------------------
> "She knows there's no success like failure
> And that failure's no success at all."
> -Bob Dylan-
> ------------------------------------------------------------
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list