Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
The very basics of text files
with statement and exception handling
13. Summary


All right, it's time to wrap things up!

  • To open and close a file, use:

    file = open('filename')
  • reads the contents of the given file.
  • file.write('text') writes 'text' to the given file.
  • open('filename', 'mode') can use, among others, the following modes:
    • 'r'read only;
    • 'w'write only – by creating or replacing an existing file;
    • 'a'append – add contents to the end of the file;
  • To read a file line by line, use:
    file = open('filename')
    for line in file:
  • The with statement can be used to automatically close a file:
    with open('filename') as file:
  • To handle exceptions, use:
    except ErrorType:
  • ErrorTypes include IOError and ValueError, but there are many more.

Are you ready for a short quiz now?


Click Next exercise to continue.