CBSE Class 12 Computer Science Question 90 of 145

File Handling — Question 7

Back to all questions
7
Question

Question 7

When a file is opened for output in write mode, what happens when

(i) the mentioned file does not exist

(ii) the mentioned file does exist ?

Answer

When a file is opened for output in write mode ("w" mode) in Python, the behaviour differs depending on whether the mentioned file already exists or not:

(i) If the mentioned file does not exist — If the file specified in the open() function does not exist, Python will create a new file with the given name. The file will be opened for writing, and any data written to it will be written from the beginning of the file.

(ii) If the mentioned file does exist — If the file specified in the open() function already exists, Python will truncate existing data and over-write in the file. It's essential to be cautious when opening existing files in write mode, as any existing data will be lost when the file is opened in "w" mode.