Bird
0
0

Which file mode should you use in Python to open a file for writing only, creating the file if it does not exist and truncating it if it does?

easy📝 Conceptual Q1 of 15
Python - File Handling Fundamentals
Which file mode should you use in Python to open a file for writing only, creating the file if it does not exist and truncating it if it does?
A"x"
B"w"
C"a"
D"r"
Step-by-Step Solution
Solution:
  1. Step 1: Understand the purpose of each file mode

    "w" mode opens a file for writing, creates it if missing, and truncates existing content.
  2. Step 2: Compare with other modes

    "r" is for reading only, "a" appends without truncating, "x" creates but errors if file exists.
  3. Final Answer:

    "w" mode -> Option B
  4. Quick Check:

    Write mode = w [OK]
Quick Trick: Use "w" to write and overwrite files [OK]
Common Mistakes:
  • Confusing "w" with "a" which appends
  • Using "r" which is read-only
  • Using "x" which errors if file exists

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes