KnowledgeBoat Logo

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.

Python

Python File Handling

2 Likes

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.

Answered By

2 Likes


Related Questions