Bird
Raised Fist0

Which of the following Python code snippets correctly opens a file named 'data.txt' and reads its entire content into a variable text?

easy🧠 Conceptual Q2 of Q15
Python - File Reading and Writing Strategies
Which of the following Python code snippets correctly opens a file named 'data.txt' and reads its entire content into a variable text?
Awith open('data.txt') as f: text = f.readlines()
Bfile = open('data.txt') text = file.readline() file.close()
Cwith open('data.txt', 'r') as f: text = f.read()
Dfile = open('data.txt', 'w') text = file.read() file.close()
Step-by-Step Solution
Solution:
  1. Step 1: Opening file for reading

    with open('data.txt', 'r') as f: text = f.read() uses open with mode 'r' (read) and a with statement for safe handling.
  2. Step 2: Reading entire content

    with open('data.txt', 'r') as f: text = f.read() calls f.read() which reads the whole file content into text.
  3. Step 3: Other options

    file = open('data.txt') text = file.readline() file.close() reads only one line with readline(). with open('data.txt') as f: text = f.readlines() reads lines into a list, not a string. file = open('data.txt', 'w') text = file.read() file.close() opens file in write mode, so reading is invalid.
  4. Final Answer:

    with open('data.txt', 'r') as f: text = f.read() correctly reads entire file content.
  5. Quick Check:

    Use with open(..., 'r') and read() for full content [OK]
Quick Trick: Use with open('file', 'r') and read() to get full content [OK]
Common Mistakes:
MISTAKES
  • Using write mode 'w' when intending to read.
  • Using readline() instead of read() to get full content.
  • Not closing the file or not using with statement.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes