Open function

The open function in Python is used to open files.

Open takes two string arguments, and returns a file object. The syntax is

myFile = open('filename', 'mode')

Usually, filename will be a text file ending in .txt. By default Python only looks for files in the same directory as your program, so make sure anything you want to use in your programs is saved there. If you create and save the file in IDLE this will be done automatically.

For the purposes of Intro to Programming, the mode will be one of three things:

  • 'r' opens an existing file for reading.
  • 'w' opens a file for writing. If the file doesn't exist Python will create it for us. If it does exist it will be written over - its previous contents will be lost.
  • 'a' (short for append) also opens a file for writing. However, unlike 'w', if we open an existing file its contents won't be overwritten. Instead, as the name suggests, this mode appends your new content to the end of the file.

See Also

Python 3.2 Documentation

Invalid username
Login to AoPS