Mike McMahon's answer is correct that the value assigned to the email
variable will be available outside the loop. However, The function he shows is rather fragile. If your file doesn't have any lines that start with "From"
, the variable will never be assigned and you'll get an exception when you try to print it. Furthermore, if multiple lines meet the conditions (e.g. starting with "From"
), you'll only see the last one. If you want the first, you'll need to change things up.
Here's a better structure:
emails = []
for line in handle:
line = line.rstrip()
if line.startswith('From'):
words = line.split()
if words[0] == 'From':
emails.append(words[1])
I find the nested if
blocks easier to understand than the repeated continue
statements, though this is something of a stylistic choice. This version makes a list of all the values it finds. The list may be empty (if there are no lines that start with From
, or it may have one or more results.
If you want the first result only, and not finding any is an error, here's another approach:
for line in handle:
line = line.rstrip()
if line.startswith('From'):
words = line.split()
if words[0] == 'From':
emails = words[1]
break
else:
raise ValueError("No 'From' line found!")
# you can use the email variable here!
An else
block attached to a for
loop is run only if the loop runs to completion. If a break
statement is hit in the loop body, the else
block will be skipped. It can be very useful in situations like this, where you are looking for the first match, and not finding one is an error.