Which of the following is the correct Python statement to open a text file “example.txt” in both read and write mode?
Which of the following is the correct Python statement to open a text file “example.txt” in both read and write mode?
Solution
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.
Related questions:
2025: 16 May Shift 1