Q. Consider the file p2.txt created above. Now predict the output of following code that works with p2.txt. Explain the reason behind this output.


fp1= open("p2.txt", "r")

print (fp1.readline(20))

s1= fp1.readline (30)

print(s1)

print (fp1.readline (25))


Answer :-

The output produced by above code will be:-

A poem by Paramhansa
  Yogananda
Better than Heaven or Arc


The reason behind this output is that the first file-read line (i.e., fp1.readline (20), read 20 bytes from the pointer. As just after opening the file, the file-pointer is at the beginning of the file, the 20 bytes are read from the beginning of the file which returned string as "A poem by Paramhansa\n"- this is because readline() returns the read string by adding an end-line character to it (\n). So the first line of output was printed as:


A poem by Paramhansa

After the first readline(), the file pointer was at the space following word 'Paramhansa', so the next readline() started reading from there and read 15 character or end-of the-line, whichever is earlier. So the read string was "Yogananda\n" - notice the space before word Yogananda. Hence came the second line of the output.

Now the file-pointer was at the beginning of the third line and the next readline (i... fp1.readline(25)) read 25 characters from this line and gave the last line of output.

Post a Comment

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

Previous Post Next Post