Introduction
The very basics of text files
with statement and exception handling
Summary
13. Summary

Instruction

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

  • To open and close a file, use:

    file = open('filename')
    ...
    file.close()
    
  • file.read() 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:
      ...
    file.close()
    
  • The with statement can be used to automatically close a file:
    with open('filename') as file:
      ...
    
  • To handle exceptions, use:
    try:
      ...
    except ErrorType:
      ...
    
  • ErrorTypes include IOError and ValueError, but there are many more.

Are you ready for a short quiz now?

Exercise

Click Next exercise to continue.