Identify the correct program code to open the text file in write mode only.
Note:(If the file already exists, all the contents will be overwritten. If the file doesn’t exist, then a new file will be created.)
Identify the correct program code to open the text file in write mode only.
Note:(If the file already exists, all the contents will be overwritten. If the file doesn’t exist, then a new file will be created.)
Solution
Mode "w" opens a text file for writing only. If the file exists, its contents are erased, and if it doesn't exist, a new file is created. This matches the conditions in the question.
Option 1: "a+" opens for appending and reading. It keeps the old contents and adds new data at the end.
Option 3: "wb" is write-only, but in binary mode, not text mode.
Option 4: "w+" also overwrites the file, but it allows reading as well, so it is not write mode only.
A "+" in a mode always adds the other operation (reading or writing). Without it, the mode is single-purpose.
Related questions:
2026: 21 May Shift 1
2025: 21 May Shift 1