[Type B] File Handling – Chapter 5 Sumita Arora

|
Table of Contents

5. 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:

Python
file1 = open ("E:\\mydata\\poemBTH.txt", "r+")

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.

Code Analysis: Line 1 of the code opens the file in read-write mode.

(a)
print ("A. Output 1")
print (file1.read())
print ()

Output
A. Output 1
God made the Earth;
Man made confusing 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)
print ("B. Output 2")
print (file1.readline())
print ()

Output
B. Output 2
God made the Earth;

This code reads the first line of the file and prints it.

State of file1 after (a) and (b):

The file pointer is positioned at the beginning of the second line after reading everything in (a) and the first line in (b).

(c)
print ("C. Output 3")
print (file1.read(9))
print ()

Output
C. Output 3
Man made c

This code reads up to 9 characters from the file, starting from the current file pointer position (beginning of the second line). It displays the first 9 characters of the second line, which is “Man made c”.

State of file1 after (c):

The file pointer is 9 characters ahead from its previous position (after reading the first 9 characters of the second line).

(d)
print ("D. Output 4")
print (file1.readline(9))

Output
D. Output 4
onfusing

This code reads up to 9 characters from the file starting from the current position (9 characters into the second line). It displays the next “9” characters from the second line, which is “onfusing “.

State of file1 after (d):

The file pointer will be at the end of the second line or 9 characters further, depending on which comes first. In this case, it’s at the end of the second line.

(e)
print ("E. Output of Readlines function is")
print (file1.readlines())
print ()

Output
E. Output of Readlines function is
['And their fancy-frozen boundaries.\n', 'But with unfound boundless Love\n', 'I behold the borderland of my India\n', 'Expanding into the world.\n', 'Hail, mother of religions, lotus, scenic beauty, and sages!\n']

This code reads all remaining lines of the file into a list and prints them. It displays all remaining lines of the poem after the second line, as a list of strings.

"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment