code to parse a file

Justin Sheehy dworkin at ccs.neu.edu
Thu Feb 10 10:49:29 EST 2000


"Pedro Silva" <psilva at ruido-visual.pt> writes:

>         f=open('/var/spool/news/articles/esoterica/geral/1','r')
>         for lines in f.readline():
>             if string.find('From:'):
>                 from=lines
>             if string.find('Subject:'):
>                 sub=lines
>             if string.find('Date:'):
>                 date=lines
>             if string.find('Xref:'):
>                 f.seek(0,2)
>                 for text in f.read():
>                         cont=text
>         return from,sub,date,cont
> 
> Is this code correct to do what I pretend?

That may work much of the time, but you'll probably end up with a
more reliable script if you use the standard rfc822 library instead.
Messages like the ones you are looking at can be parsed like this:

>>> import rfc822
>>> msg = rfc822.Message(open('/var/spool/news/control/1'))
>>> msg.getheader('From')
'Justin Sheehy <justin at iwant.com>'
>>> msg.getheader('Subject')
'cancel <37D8021C.1EB4DF3A at iwant.com>'
>>> msg.getheader('Date')
'Thu, 09 Sep 1999 14:54:38 -0400'
>>> msg.rewindbody()
>>> msg.fp.read()
'This message was cancelled by Justin Sheehy.\012'

-Justin

 




More information about the Python-list mailing list