File I/O

In this lesson, you'll learn how to read and write files in Python.

Introduction to file handling

To read or write a file, you must do three things:

  1. Open the file
  2. Use the file (reading or writing)
  3. Close the file

Opening files in Python

The file = open(file_name, mode) command opens and returns (in the variable file) a reference to the named file. In this case, mode would be one of the following:

  • r to read the file (This is the default if mode is omitted).
  • w to erase and write the file.
  • a to append to the end of an existing file.
  • r+ to both read and write.
  • rb, wb, ab, and
...