Introduction to Programming Using Python — Question 3

You develop a Python application for your school.
You need to read and write data to a text file. If the file does not exist, it must be created. If the file has content, the content must be removed.
Which code should you use?

Answer options

Correct answer: C

Explanation

The correct answer is C, as using 'w+' opens the file for both reading and writing, and it creates the file if it doesn't exist while also truncating any existing content. Option A will only allow reading from the file, and option B allows reading and writing but does not clear existing content. Option D will create the file and remove its content, but it does not allow reading from it.