Pritish Pandit
Pritish Pandit

Reputation: 21

Confusing way readline() is operating

I am confused about how the infile.readline() function is operating in my code.

NOTE: Python interpreter v2.7.15(64-bit) is being used.

infile = open(r'C:\Users\pritish\Desktop\test_file_for_py.txt', 'r')
print infile.read(5)
print infile.read(5)
print infile.readline(2)

Where test_file_for_py.txt contains these lines:

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8

In the above #TEST CODE 1 , print infile.readline(2), gives output ne, which is as expected:

>>> infile = open(r'C:\Users\pritish\Desktop\test_file_for_py.txt', 'r')
>>> print infile.read(5)
This
>>> print infile.read(5)
is li
>>> print infile.readline(2)
ne
>>>

Now here's the catch, it keeps giving same result as below, no matter which value (greater than 4) I pass as an argument to infile.readline().

>>> infile = open(r'C:\Users\pritish\Desktop\test_file_for_py.txt', 'r')
>>> print infile.read(5)
This
>>> print infile.read(5)
is li
>>> print infile.readline(5) # NOTE BELOW output
ne 1

>>>
>>> infile = open(r'C:\Users\pritish\Desktop\test_file_for_py.txt', 'r')
>>> print infile.read(5)
This
>>> print infile.read(5)
is li
>>> print infile.readline(8) #value is changed to 8 now , but still o/p same as previous(as like 5)
ne 1

>>>

Can anyone please explain, why infile.readline() is not returning characters from the next line even though I change infile.readline() argument to whatever value (>5)?

Upvotes: 0

Views: 48

Answers (1)

iz_
iz_

Reputation: 16573

readline stops when it reaches a new-line character. The optional size argument specifies how many characters to read at most. If it encounters a newline before size characters are read, it stops anyway, and the size argument becomes irrelevant.

See the documentation.

Upvotes: 3

Related Questions