Bird
Raised Fist0

Which of these is the correct way to open a file for writing in Python?

easy📝 Syntax Q3 of Q15
Python - File Handling Fundamentals
Which of these is the correct way to open a file for writing in Python?
Afile = open('data.txt', 'z')
Bfile = open('data.txt', 'r')
Cfile = open('data.txt', 'x')
Dfile = open('data.txt', 'w')
Step-by-Step Solution
Solution:
  1. Step 1: Recall file modes in Python

    'w' mode opens a file for writing, creating it if it doesn't exist.
  2. Step 2: Check each option's mode

    'r' is for reading, 'x' is for exclusive creation, 'z' is invalid.
  3. Final Answer:

    file = open('data.txt', 'w') -> Option D
  4. Quick Check:

    Write mode = 'w' [OK]
Quick Trick: Use 'w' mode to write or overwrite files [OK]
Common Mistakes:
MISTAKES
  • Using 'r' mode to write files
  • Using invalid mode letters like 'z'
  • Confusing 'x' mode with 'w' mode

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes