Page 146 -
P. 146

open and close


           Open your file in write mode


           When you use the open() BIF to work with a disk file, you can specify an
           access mode to use. By default, open() uses mode r for reading, so you don’t
           need to specify it. To open a file for writing, use mode w:        The access model
                                                                              to use




                         The data file    out = open("data.out", "w")
                         object
                                                           The name of the file to
                                                            write to


           By default, the print() BIF uses standard output (usually the screen) when
           displaying data. To write data to a file instead, use the file argument to
           specify the data file object to use:



                           print("Norwegian Blues stun easily.", file=out)


                                                                                The name of the data
                  What gets written to the file
                                                                                file object to write to
           When you’re done, be sure to close the file to ensure all of your data is written
           to disk. This is known as flushing and is very important:



                                                                            This is VERY important
                                                   out.close()              when writing to files.





                                          Geek Bits




                                 When you use access mode w, Python opens your named file
                                 for writing. If the file already exists, it is cleared of its contents, or
                                 clobbered. To append to a file, use access mode a, and to open a
                                 file for writing and reading (without clobbering), use w+. If you
                                 try to open a file for writing that does not already exist, it is first
                                 created for you, and then opened for writing.



           110    Chapter 4
   141   142   143   144   145   146   147   148   149   150   151