Regular expressions in files

Ken Kinder kkinder at my-deja.com
Sun May 21 04:47:12 EDT 2000


Use the normal regular expression API (I don't know it) against
individual lines as you read them in:

fd = open('filename')
text = ''

line = fd.readline()
while line:
	... here, include your code to test line
	... matching the re. If the re matches, you
	... may care to use the break statement to end
	... the loop early
	line = fd.readline()

... if it got down here and the re never tested true,
... it wasn't in the file

fd.close()

In article <39254357.C7988097 at uwe.ac.uk>,
  Simon Langley <Simon.Langley at uwe.ac.uk> wrote:
> Can regular expression matching be done on files?  I'd like to read
just
> as much of a file as is necessary to either be a (greedy) match of the
> re or until a match definitely can't be found.
>
> If a string is read from a file, tried for a match and fails can I
tell
> whether it failed because a) without reaching the end of the string it
> didn't match or b) it didn't match by the end of the string but might
> have if the next line had been appended?  That would solve the
problem.
>
> Thanks,
>
> Simon
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Simon Langley
> Email: Simon.Langley at uwe.ac.uk
> University of the West of England
> Bristol BS16 1QY
> England
>
>

--
Ken Kinder


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list