Bird
Raised Fist0

What will be the output of the following code?

medium📝 Predict Output Q13 of Q15
Python - File Handling Fundamentals
What will be the output of the following code?
file = open('example.txt', 'w')
file.write('Hello')
file.close()
file = open('example.txt', 'r')
print(file.read())
file.close()
A'' (empty string)
Bexample.txt
CHello
DError: file not found
Step-by-Step Solution
Solution:
  1. Step 1: Write 'Hello' to the file

    The file is opened in write mode, 'Hello' is written, then the file is closed to save changes.
  2. Step 2: Read the content back

    The file is reopened in read mode, and read() returns the string 'Hello' which is printed.
  3. Final Answer:

    Hello -> Option C
  4. Quick Check:

    Write then read returns written text [OK]
Quick Trick: Write then close before reading to see content [OK]
Common Mistakes:
MISTAKES
  • Not closing file before reading
  • Expecting filename as output
  • Assuming empty string without write

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes