Exceptions & Files · Question 5 · Easy

A file report.txt already has some text in it. What happens to that text when the file is opened with open("report.txt", "w")?

  1. It is kept, and new text is added after it
  2. It is erased, and writing starts from an empty file
  3. It is kept, and the file is opened read-only
  4. Nothing happens to it, because Python raises FileExistsError
Answer and explanation

Answer: B. It is erased, and writing starts from an empty file

Explanation: Mode "w" truncates an existing file to zero length as soon as it is opened. Use "a" to add at the end, and "x" if you want an error when the file already exists.

Previous: A dictionary of marks is asked for a name that was never stored. Which… · Next: The try block below completes without any error and the statement has an else…

Practise exceptions & files

Try a fresh set of exceptions & files questions with an explanation after every answer, free and without signing up: Exceptions & Files practice. Or sit a full placement mock test.

More exceptions & files questions

More python practice

Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge