Bird
0
0

Which of the following is the correct syntax to open a file named 'data.txt' for writing in Python?

easy📝 Syntax Q12 of 15
Python - Standard Library Usage
Which of the following is the correct syntax to open a file named 'data.txt' for writing in Python?
Aopen('data.txt', 'r')
Bopen('data.txt', 'w')
Copen('data.txt', 'rw')
Dopen('data.txt', 'a+')
Step-by-Step Solution
Solution:
  1. Step 1: Identify the mode for writing

    The mode 'w' opens a file for writing and creates it if it doesn't exist or overwrites if it does.
  2. Step 2: Check syntax correctness

    open('data.txt', 'w') is the correct syntax. 'r' is for reading, 'rw' is invalid, 'a+' is for appending and reading.
  3. Final Answer:

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

    Write mode = 'w' [OK]
Quick Trick: Use 'w' to write or overwrite files [OK]
Common Mistakes:
  • Using 'r' when intending to write
  • Using invalid mode 'rw'
  • Confusing 'a+' with 'w'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes