Skip to content
Question

Q.Which of the following modes in Python creates a new file, if file does not exist and overwrites the content, if the file exists ?

(a) r+
(b) r
(c) w
(d) a
CBSECBSE Class XII Board 2023MCQ· 1mImportance★★★★★
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

The 'w' (write) mode in Python creates a new file if it doesn't exist and overwrites all existing content if the file already does.

When working with files in Python, we often need to specify how we intend to interact with the file. This is done through what are called "modes" when opening a file. These modes dictate whether you want to read from the file, write to it, append new content, or a combination of these actions, and also define how the system should behave if the file doesn't exist or already contains data. Understanding these modes is fundamental to effective file handling.

Let's look at the common file modes:

  • 'r' (Read Mode):

    This is the default mode. When you open a file in read mode, you can only read its contents. You cannot modify or add new data.

    Watch out

    If the file you are trying to open in 'r' mode does not exist, Python will raise a FileNotFoundError. It will never create a new file in this mode.

  • 'r+' (Read and Write Mode):

    This mode allows you to both read from and write to a file. The file pointer is initially at the beginning of the file.

    Important

    Similar to 'r' mode, if the file does not exist when opened in 'r+' mode, Python will raise a FileNotFoundError. It does not create a new file. If the file exists, writing will occur from the current position of the file pointer, potentially overwriting existing content from that point onwards.

  • 'w' (Write Mode):

    This mode is specifically for writing data to a file. It has a very distinct behavior regarding file existence:

    • If the file does not exist, Python will create a new, empty file with the specified name. …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.