Help with readline() & readlines()

I’ve been reviewing what I’ve learnt sofar in code the hardway.
I think I understand everything, except there is one thing that is bugging me as I don’t seem to understand it properly and it seems so basic.
I’ve looked online, but still not getting it - so hope someone can point me in the right direction.

I got a test.txt document with some lines of text, and I want to read line no two.
I tried with the below two versions.

I would have thought that print(openfile.readlines(2)) would give me what I want but it only reads the first line.
How do I jump to line two without making the ‘loop’ as in exercise 20?

openfile = open('test.txt', 'r')

#Read only first line in test.txt
print(openfile.readlines(2))

#Reads first two letters in first line, which makes sense as the 'reading head' has 'rewinded'
openfile.seek(0)
print(openfile.readline(2))

Take a look here:

https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

And

https://docs.python.org/3/library/io.html#io.IOBase.readline

And

https://docs.python.org/3/library/io.html#io.IOBase.readlines

The thing to remember is how you think it should work really doesn’t matter. All that matters is how they did it, even if how they did it seems dumb. In fact, if you think it’s dumb then most likely you just don’t understand something about it that explains why they did that.

1 Like