Computer Science
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
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.
Related Questions
Write a program to add two more employees' details (empno, ename, salary, designation) to the file "emp.txt" already stored in disk.
How are the following codes different from one another?
1.
fp = open("file.txt", 'r') fp.read()
2.
fp = open("file.txt", 'r')
Write the output of the following code with justification if the contents of the file "ABC.txt" are:
"Welcome to Python Programming!"
f1 = open("ABC.txt", "r") size = len(f1.read()) print(size) data = f1.read(5) print(data)
Give the output of the following snippet:
import pickle list1, list2 = [2, 3, 4, 5, 6, 7, 8, 9, 10], [] for i in list1: if (i % 2 == 0 and i % 4 == 0): list2.append(i) f = open("bin.dat", "wb") pickle.dump(list2, f) f.close() f = open("bin.dat", "rb") data = pickle.load(f) f.close() for i in data: print(i)