9.3.1 Writing to a Text File: Introducing the with Statement

  • Many applications acquire resources
    • files, network connections, database connections and more
  • Should release resources as soon as they’re no longer needed
  • Ensures that other applications can use the resources
  • with statement
    • Acquires a resource and assigns its corresponding object to a variable
    • Allows the application to use the resource via that variable
    • Calls the resource object’s close method to release the resource
In [1]:
with open('accounts.txt', mode='w') as accounts:
    accounts.write('100 Jones 24.98\n')
    accounts.write('200 Doe 345.67\n')
    accounts.write('300 White 0.00\n')
    accounts.write('400 Stone -42.16\n')
    accounts.write('500 Rich 224.62\n')
  • Can also write to a file with print, which automatically outputs a \n, as in
    print('100 Jones 24.98', file=accounts)
    
In [2]:
# macOS/Linux Users: View file contents
!cat accounts.txt
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
In [ ]:
# Windows Users: View file contents
!more accounts.txt

Built-In Function open

  • Opens the file accounts.txt and associates it with a file object
  • mode argument specifies the file-open mode
    • whether to open a file for reading from the file, for writing to the file or both.
  • Mode 'w' opens the file for writing, creating the file if it does not exist
  • If you do not specify a path to the file, Python creates it in the current folder
  • Be careful—opening a file for writing deletes all the existing data in the file
  • By convention, the .txt file extension indicates a plain text file

Writing to the File

  • with statement assigns the object returned by open to the variable accounts in the as clause
  • with statement’s suite uses accounts to interact with the file
    • file object’s write method writes one record at a time to the file
  • At the end of the with statement’s suite, the with statement implicitly calls the file object’s close method to close the file

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.