Q. Consider the file “SarojiniPoem.txt”

 

Autumn Song

 

Like a joy on the heart of a sorrow,

The sunset hangs on a cloud;

A golden storm of glittering sheaves,

Of fair and frail and fluttering leaves,

The wild wind blows in a cloud.

 

Hark to a voice that is calling

To my heart in the voice of the wind:

My heart is weary and sad and alone,

For its dreams like the fluttering leaves have gone,

And why should I stay behind?

 

Sarojini Naidu

 

 

Based on the above file, answer the following question:

 

(a) What would be the output of following code?

 

file = open ("sarojiniPoem.txt","r")

text = file.readlines()

file.close()

for line in text  :

    print (line , end = ' ' )

print ( )

 

(b) Modify the program so that the lines are printed in reverse order.

 

(c) Modify the code so as to output to another file instead of the screen. Let your script overwrite the output file.

 

(d)Change the script of part (c) that it append output to an existing file.

 

(e) Modify the program so that each line is printed with a line number at beginning.

 

 

Answer =

 




(a)

It will print all the data of file, like that manner in which data are saved in file.


(b)

file = open ("sarojiniPoem.txt","r")

text = file.readlines()

for i in text:

    for j in range(-1,-len(i)-1,-1) :

        print (i[j] , end = "")

    print()

file.close()

 

(c)

file = open ("sarojiniPoem.txt","r")

out = open("output.txt","w")

text = file.readlines()

 

for i in text:

    for j in range(-1,-len(i)-1,-1) :

        out.write(i[j])

    out.write("\n") 

 

file.close()

out.close()

 

(d)

file = open ("sarojiniPoem.txt","r")

out = open("output.txt","a")

text = file.readlines()

 

for i in text:

    for j in range(-1,-len(i)-1,-1) :

        out.write(i[j])

    out.write("\n")

 

file.close()

out.close()

 

(e)

file = open ("sarojiniPoem.txt","r")

text = file.readlines()

file.close()

for i in range (len(text)):

    print (i+1 ," = ", text[i] )

 

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post