Page 206 -
P. 206
statement to function
You were to take a few moments to implement the review team’s suggestion to turn those four
with statements into a function. In the space provided, your were to create a function to
abstract the required functionality, then provide one example of how you would call your new
function in your code:
with open('james.txt') as jaf:
data = jaf.readline()
james = data.strip().split(',')
with open('julie.txt') as juf:
data = juf.readline()
julie = data.strip().split(',')
with open('mikey.txt') as mif:
data = mif.readline()
mikey = data.strip().split(',')
with open('sarah.txt') as saf:
data = saf.readline()
sarah = data.strip().split(',')
Accept a filename as
the sole argument.
Create a new def get_coach_data(filename):
function. try: Open the file, and
with open(filename) as f: read the data.
Add the suggested
exception-handling data = f.readline() Perform the split/strip trick on
code.
return(data.strip().split(‘,')) the calling code.
the data prior to returning it to
except IOError as ioerr:
print(‘File error: ' + str(ioerr))
return(None) T ell your user about the error
(if it occurs) and return “None”
to indicate failure.
Calling the function sarah = get_coach_data(‘sarah.txt')
is straightforward.
Provide the name of the file to
process.
170 Chapter 5