Page 178 -
P. 178

let’s split




                              Let’s begin by reading the data from each of the files into its own list. You were to write a short
                              program to process each file, creating a list for each athlete’s data. You were then to display the
                              lists on screen.                           Open the file.
                                             with open(‘james.txt’) as jaf:

                                                 data = jaf.readline()       Read the line of data.

                                             james = data.strip().split(‘,’)  Convert the data to a list.

                                             with open(‘julie.txt’) as juf:
                                                 data = juf.readline()
                Open each of
                the data files               julie = data.strip().split(‘,’)
                 in turn, read
                 the line of                 with open(‘mikey.txt’) as mif:
                 data from the
                 file, and create                data = mif.readline()
                 a list from the
                 line of data.               mikey = data.strip().split(‘,’)
                                             with open(‘sarah.txt’) as saf:

                                                 data = saf.readline()

                                             sarah = data.strip().split(‘,’)



                                             print(james)

                                             print(julie)

                                             print(mikey)           Display the four lists on screen.
                                             print(sarah)







           Q:   That data.strip().split(',') line looks a little weird. Can you explain what’s going on?



          A: That’s called method chaining. The first method, strip(), is applied to the line in data, which removes any unwanted whitespace
           from the string. Then, the results of the stripping are processed by the second method, split(','), creating a list. The resulting list is
           then applied to the target identifier in the previous code. In this way, the methods are chained together to produce the required result. It helps
           if you read method chains from left to right.
           142    Chapter 5
   173   174   175   176   177   178   179   180   181   182   183