Computer Science
Consider the file "poemBTH.txt" and predict the outputs of following code fragments if the file has been opened in filepointer file1 with the following code :
file1 = open("E:\\mydata\\poemBTH.txt", "r+")
(a)
print("A. Output 1")
print(file1.read())
print()
(b)
print("B. Output 2")
print(file1.readline())
print()
(c)
print("C. Output 3")
print(file1.read(9))
print()
(d)
print("D. Output 4")
print(file1.readline(9))
(e)
print("E. Output of Readlines function is")
print(file1.readlines())
print()
NOTE. Consider the code fragments in succession, i.e., code (b) follows code (a), which means changes by code (a) remain intact when code (b) is executing. Similarly, code (c) follows (a) and (b), and so on.
Answer
As mentioned in the note, the output of above code fragments together in succession is as follows:
A. Output 1
God made the Earth;
Man made confining countries
And their fancy-frozen boundaries.
But with unfound boundLess Love
I behold the borderLand of my India
Expanding into the World.
HaiL, mother of religions, Lotus, scenic beauty, and sages!
B. Output 2
C. Output 3
D. Output 4
E. Output of Readlines function is
[]
Working
After executing file1.read()
in code snippet (a), the file pointer will be moved to the end of the file (EOF) because all the content has been read. Therefore, subsequent read operations, such as file1.readline(), file1.read(9), and file1.readlines()
, will start from the end of the file (EOF) and will not read any further content, resulting in empty outputs for those print statements.
Related Questions
Consider the file poemBTH.txt given above (in previous question). What output will be produced by following code fragment ?
obj1 = open("poemBTH.txt", "r") s1 = obj1.readline() s2.readline(10) s3 = obj1.read(15) print(s3) print(obj1.readline()) obj1.close()
Write code to open file contacts.txt with shown information and print it in following form :
Name: <name> Phone: <phone number>
What is the following code doing ?
file = open("contacts.csv", "a") name = input("Please enter name.") phno = input("Please enter phone number.") file.write(name + "," + phno + "\n")
Consider the file "contacts.csv" created in above Q. and figure out what the following code is trying to do?
name = input("Enter name :") file = open("contacts.csv", "r") for line in file: if name in line: print(line)