CBSE Class 12 Computer Science Question 100 of 136

Data File Handling — Question 39

Back to all questions
39
Question

Question 39

What is the output of the following code fragment? Explain.

fout = open("output.txt", 'w') 
fout.write("Hello, world! \n") 
fout.write("How are you?") 
fout.close()
f = open("output.txt")
print(f.read())
Answer
Output
Hello, world! 
How are you?

The code first opens a file named 'output.txt' in write mode ('w'), writes the strings 'Hello, world!' and 'How are you?' to the file with a newline character in between, creating a new line between the two strings in the file. It then closes the file and reopens it again in read mode (default mode). Finally, it reads the entire content of the file and prints it.