Computer Science
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)
Answer
30
The code opens the file 'ABC.txt' in read mode ('r') and creates a file object named f1
. The next line, size = len(f1.read())
, reads the entire contents of the file 'ABC.txt', returning a string containing the file's contents. Then, len()
calculates the length of this string and assigns it to the variable size
. After the f1.read()
operation, the file pointer is positioned at the end of the file. The code then prints the size
. The subsequent line, data = f1.read(5)
, attempts to read the first 5 characters from the file 'ABC.txt' using f1.read(5)
. However, since the file pointer is already at the end of the file, there are no characters left to read. Therefore, this read(5)
operation will return an empty string. Finally, the code prints the value of data
, which is an empty string.
Related Questions
How are the following codes different from one another?
1.
fp = open("file.txt", 'r') fp.read()
2.
fp = open("file.txt", 'r')
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())
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)
Anant has been asked to display all the students who have scored less than 40 for Remedial Classes. Write a user-defined function to display all those students who have scored less than 40 from the binary file "Student.dat".