Page 111 -
P. 111

files and exceptions


           It’s all lines of text


           The basic input mechanism in Python is line based: when read into your
           program from a text file, data arrives one line at a time.

           Python’s open() BIF lives to interact with files. When combined with a for
           statement, reading files is straightforward.




        Your data in a text
        file called “sketch.txt”.






                                                                                                  Your data
                                                  open()                                          as individual
                                                                                                 lines.








           When you use the open() BIF to access your data in a file, an iterator is
           created to feed the lines of data from your file to your code one line at a time.
           But let’s not get ahead of ourselves. For now, consider the standard open-
           process-close code in Python:


                                                                                              Do this!



          Open…         the_file = open('sketch.txt')

                                                                                Create a folder called
                       # Do something with the data                             HeadFirstPython and a
        …Process…
                       # in "the_file".                                         subfolder called chapter3.
                                                                                With the folders ready,
           …Close.     the_file.close()                                         download sketch.txt from
                                                                                the Head First Python support
                                                                                website and save it to the
                                                                                chapter3 folder.


           Let’s use IDLE to get a feel for Python’s file-input mechanisms.


                                                                                       you are here 4    75
   106   107   108   109   110   111   112   113   114   115   116