Skip to main contentSkip to solution

Which of the following is the correct Python statement to open a text file “example.txt” in both read and write mode?

Solution

✅ Correct Option: 2

The mode "r+" opens an existing text file for both reading and writing. The file pointer starts at the beginning, and the file must already exist, otherwise Python raises a FileNotFoundError.


Option 1: "r" is read-only, so writing raises an error.

Option 3: "w" is write-only, and it also erases the existing content (or creates a new file). It does not allow reading.

Option 4: "a" is append-only. It writes at the end of the file and does not allow reading.

For read and write with other behaviours, "w+" erases the file first, and "a+" appends and also allows reading.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question