H Ron,
>>> import re
>>> f = open('c:/lines.txt').readlines()
>>> for line in f:
match = re.search('^This',f)
if line == match:
print match
Hi Ron,
Welcome to the wonderful world of Python.
from re.search.__doc__ ;
"Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."
OK, so if there's a match, you get an object returned, otherwise it
returns None. So, you can boolean test this. I'm guessing you want to
print lines that start with this.
import re
f = file('c:/lines.txt) #Also, you can iterate over a file
for line in f:
match = re.search('^This', line) #you want to search line by line?
if match:
print line
else:
print "No match"
Or, you could store all the lines in a list to use afterwards -
lineStore =[]
for line in f:
match = re.search('^This', line) #you want to search line by line?
if match:
lineStore.append(line)
else:
print "No match"
On Tue, 8 Feb 2005 21:36:55 -0800 (PST), Ron Nixon <[EMAIL PROTECTED]> wrote:
> Can anyone tell me what I've done wrong in this
> script.
>
> I'm trying to get only the lines that start with
> "This" for a text file.
>
> Here's what I wrote:
>
> >>> import re
> >>> f = open('c:/lines.txt').readlines()
> >>> for line in f:
> match = re.search('^This',f)
> if line == match:
> print match
>
> here's the error message I got:
>
> Traceback (most recent call last):
> File "<pyshell#34>", line 2, in -toplevel-
> match = re.search('^This',f)
> File "C:\Python24\lib\sre.py", line 134, in search
> return _compile(pattern, flags).search(string)
> TypeError: expected string or buffer
>
> Thanks in advance
>
>
> __________________________________
> Do you Yahoo!?
> Read only the mail you want - Yahoo! Mail SpamGuard.
> http://promotions.yahoo.com/new_mail
> _______________________________________________
> Tutor maillist - [email protected]
> http://mail.python.org/mailman/listinfo/tutor
>
--
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor