with Statement¶with statement close method to release the resourcewith 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')
print, which automatically outputs a \n, as inprint('100 Jones 24.98', file=accounts)
# macOS/Linux Users: View file contents
!cat accounts.txt
# Windows Users: View file contents
!more accounts.txt
open¶accounts.txt and associates it with a file objectmode argument specifies the file-open mode'w' opens the file for writing, creating the file if it does not exist.txt file extension indicates a plain text filewith statement assigns the object returned by open to the variable accounts in the as clausewith statement’s suite uses accounts to interact with the filewrite method writes one record at a time to the filewith 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.