CBSE Class 12 Computer Science Question 106 of 145

File Handling — Question 2

Back to all questions
2
Question

Question 2

If the file 'poemBTH.txt' contains the following poem (by Paramhans Yoganand) :

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!

Then what outputs will be produced by both the code fragments given in question1.

Answer

(a)

my_file = open('poemBTH.txt', 'r')
my_file.read()
Output
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!
Explanation

This code reads the entire content of the file poemBTH.txt into a single string. Since no specific number of characters is specified, it will read until the end of the file (EOF) is reached.

(b)

my_file = open('poemBTH.txt', 'r') 
my_file.read(100)
Output
God made the Earth;
Man made confining countries
And their fancy-frozen boundaries.
But with unfound 
Explanation

This code reads the first 100 characters from the file "poemBTH.txt" into a string. It is important to note that the newline at the end of each line will also be counted as a character.