Skip to main contentSkip to solution

Identify the correct python statement to open a text file "data.txt" in both read and write mode.

Solution

✅ Correct Option: 2

The mode "r+" opens an existing text file for both reading and writing, with the file pointer at the start. The file must already exist, otherwise an error is raised.


Option 1: no mode given, so the default "r" (read only) is used.

Options 3 and 4: "rw" and "rw+" are not valid modes in Python and raise a ValueError.

Other combined modes are "w+" (read and write, erases existing content) and "a+" (read and append).

Keyboard Shortcuts

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