Which of the following mode, when used in file opening statement in Python,…

2023

Which of the following mode, when used in file opening statement in Python, generates an error, if the file does not exist ?

  1. A.

    a+ / a+

  2. B.

    r+ / r+

  3. C.

    w+ / w+

  4. D.

    a / a

Attempted by 1540 students.

Show answer & explanation

Correct answer: B

Answer: r+

Explanation:

  • r+ (read and write): Requires that the file already exists. Attempting to open a non-existent file with r+ raises FileNotFoundError.

  • a+ (append and read): Opens for reading and appending; creates the file if it does not exist, so no error is raised for a missing file.

  • w+ (write and read): Opens for writing and reading; creates the file if it does not exist (and truncates it if it does), so no error is raised for a missing file.

  • a (append): Opens for appending; creates the file if it does not exist, so no error is raised for a missing file.

Conclusion: r+ is the only listed mode that generates an error when the file does not exist because it requires an existing file.

Explore the full course: Rssb Senior Computer Instructor