How does the function .readline() know which line it schould save in the variable?

How does the function .readline() know which line it schould save in the variable?

I’m currently here: Learn Python: Files Reading a Line on the first instruction.

The example is

``` with open('millay_sonnet.txt') as sonnet_doc: first_line = sonnet_doc.readline() second_line = sonnet_doc.readline() print(second_line) ```

and the explanation is as following:
" This script also creates a file object called sonnet_doc that points to the file millay_sonnet.txt. It then reads in the first line using sonnet_doc.readline() and saves that to the variable first_line. It then saves the second line (So make the most of this, your little day,) into the variable second_line and then prints it out."

how can Python know that if you which line you want to wo save inside a variable. Why is the the second line stored in the variable “second_line” whe the exact same command ( sonnet_doc.readline() ) is given. In this function there isn’t writen any argument or something else which could show the maschine that is should place the second line from the file into the variable “second_line” instead of the first line from the text. The Variable “second_line” could also be named “grasshopper”. Would Python still know that is should assing the second line in the file to the “grasshopper” variable? If Yes, Why? How? and how can i controll that?

When we open a file it comes in to memory as a consumable object. This has no effect on the file on the volume, only the content in memory. Each new call to .readline() consumes the top line of the remaining content.

If you are familiar with iterators, consider this along the same lines.

2 Likes