search a string
Carl J. Van Arsdall
cvanarsdall at mvista.com
Thu Apr 20 18:38:01 EDT 2006
Bruno Desthuilliers wrote:
> Carl J. Van Arsdall a écrit :
>
>> david brochu jr wrote:
>>
>>
>>> Hello,
>>>
>>>
>>> I have a text file with the following string:
>>> ['\r\n', 'Pinging www.ebayyy.com <http://www.ebayyy.com/>
>>> [207.189.104.86 <http://207.189.104.86>] with 32 bytes of data:\r\n',
>>> '\r\n', 'Request timed out.\r\n', '\r\n', 'Ping statistics for
>>> 207.189.104.86:\r\n', ' Packets: Sent = 1, Received = 0, Lost = 1
>>> (100% loss),\r\n']
>>>
>>>
>>> How would I search to find out if the string contained "Request" and
>>> report if "Request" was found or not in the string?
>>>
>
> <op>
> First point : this is not a string, but a list of strings. I suppose it
> comes from a file.readlines() call. If you want the whole file content
> as a single string, use file.read() instead - but take care of big files...
> </op>
>
Ha, oops, that's what I get for not wearing my glasses.
>
>> Well, there really are two ways you could go about it depending on what
>> you are more comfortable with.
>>
>> One way:
>>
>> import re
>> line = '<...>' # all that stuff from above
>> regExp = re.compile('Request')
>> if regExp.match(line):
>> print 'I found requested'
>>
>>
>
> FWIW, you could also hand-code a dedicated parser - preferably in
> assembler - then write a Python binding for it.
>
>
>> or you can use one of the string modules,
>>
>
>
So the code below confuses me:
> Or just use str object's methods...
>
> f = open('mylogfile.log')
> for line in f:
> if "Request" in line:
> print "got one"
> break
> else:
> print "no Request found in mylogfile.log"
>
> f.close()
>
With a file object, to iterate through the lines in a file don't you
have to use readlines()?
Something more like
f = open ('mylogfile.log')
for line in f.readlines():
if .....
?
--
Carl J. Van Arsdall
cvanarsdall at mvista.com
Build and Release
MontaVista Software
More information about the Python-list
mailing list