Computer Science - Class 12
Solutions to CBSE Sample Paper - Computer Science Class 12

(i) Differentiate between r+ and w+ file modes in Python

Answer

Answer by student

r+

w+

Does not truncate the file

Truncates the file

Raises an error if the file does not exist

Creates a new file if it does not exist

Detailed answer by teachoo

The r+ and w+ file modes in Python are two of the possible modes that can be used with the built-in open function.

The r+ and w+ modes are both combinations of read and write modes, but they have different behaviors:

r+

w+

Opens a file for both reading and writing. The file pointer is placed at the beginning of the file.

Opens a file for both reading and writing. If the file exists, it truncates (clears) the file before writing . If the file does not exist, it creates a new file for reading and writing.

Does not truncate (clear) the existing contents of the file before writing new data.

Truncates (clears) the existing contents of the file before writing new data.

Raises a FileNotFoundError exception if the file does not exist.

Creates a new file if it does not exist.

The main difference between r+ and w+ is that r+ preserves the existing contents of the file, while w+ deletes them. This means that r+ can be used to modify an existing file without losing any data, while w+ can be used to overwrite an existing file or create a new one.

Another difference is that r+ requires that the file already exists, while w+ does not. This means that r+ can be used to access an existing file, while w+ can be used to create a new one.

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo