KnowledgeBoat Logo
|
LoginJOIN NOW

Computer Science

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 ?

Python File Handling

4 Likes

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.

Answered By

2 Likes


Related Questions