Bird
Raised Fist0

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

easy📝 Syntax Q12 of Q15
Python - File Handling Fundamentals
Which of the following is the correct syntax to open a file named data.txt for reading in Python?
Afile = open('data.txt', 'w')
Bfile = open('data.txt', 'r')
Cfile = open('data.txt', 'x')
Dfile = open('data.txt', 'a')
Step-by-Step Solution
Solution:
  1. Step 1: Identify the mode for reading

    The mode 'r' stands for reading a file, which is the correct mode to open a file for reading.
  2. Step 2: Check other modes

    'w' is for writing (overwrites), 'x' is for creating a new file, 'a' is for appending to a file.
  3. Final Answer:

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

    Mode 'r' means read [OK]
Quick Trick: Use 'r' mode to open files for reading [OK]
Common Mistakes:
MISTAKES
  • Using 'w' mode which overwrites file
  • Using 'x' mode which fails if file exists
  • Using 'a' mode which appends instead of reading

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes