Carefully analyze the following Python program. The purpose of the program is…

2026

Carefully analyze the following Python program. The purpose of the program is to replace all occurrences of the word "Bombay" with the word "Mumbai" in a text file named "maharashtra.txt". However, certain parts of the code are missing and have been labeled as Task A, Task B, Task C and Task D. Complete the missing statements so that the program functions correctly. The file must be opened only once in a mode that allows both reading and writing.

try:
    _____________ as File:   # Task A
        Text = ______                              # Task B
        NewText = Text.replace("Bombay", "Mumbai")
        File.______                                # Task C
        ______                                     # Task D
        File.truncate()
except:
    print('File I/O Error!')

Questions:

(A) Write the missing statement for Task A to open the file in both read and write mode.

(B) Write the missing statement for Task B to read the entire content of the file and store it in the identifier Text.

(C) Write the missing statement for Task C to move the file pointer to the beginning of the file.

(D) Write the missing statement for Task D to write the modified content stored in NewText back into the file.

Show answer & explanation

(A) Task A (Open file in read + write mode):
open("maharashtra.txt", "r+")
Reason: The r+ mode allows both reading and writing without opening the file multiple times.

(B) Task B (Read complete content):
File.read()
Reason: Reads the entire file content and stores it in Text.

(C) Task C (Move file pointer to beginning):
File.seek(0)
Reason: Resets the file pointer to the start so that new content overwrites from the beginning.

(D) Task D (Write modified content):
File.write(NewText)
Reason: Writes the updated text (with “Bombay” replaced by “Mumbai”) back into the file.

Explore the full course: Hpsc Pgt Computer Science