[Tutor] String Attribute
Alan Gauld
alan.gauld at btinternet.com
Fri Jul 31 02:13:35 CEST 2015
On 30/07/15 23:51, ltc.hotspot at gmail.com wrote:
> fname = raw_input("Enter file name: ")
> if len(fname) < 1 : fname = "mbox-short.txt" # assign fname
> fh=open(fname,'r') # Open a new file handle
> for line in fh:
> print line
> if 'From' in line.split()[0] and '@' in line: sender = line.split()[2]
Note that you are overwriting sender each time through the loop.
Also [2] isa the third element, I think you want the second [1]
BTW Its probably clearer to write that last line as:
if line.startswith('From') and '@' in line:
sender = line.split()[1]
Better still may be to split the line first:
sections = line.split()
if 'FROM' in sections[0].upper() and '@' in sections:
sender = sections[1]
> print sender
And this is outside the loop so will only print the last item.
To print all of them you need to move the print inside the loop.
hth
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list