Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does readline() not work after readlines()?

In Python, say I have:

f = open("file.txt", "r")
    a = f.readlines()
    b = f.readline()
    print a
    print b

print a will show all the lines of the file and print b will show nothing.

Similarly vice versa:

f = open("file.txt", "r")
    a = f.readline()
    b = f.readlines()
    print a
    print b

print a shows the first line but print b will show all lines except the first one.

If both a and b are readlines(), a will show all the lines and b will show nothing.

Why does this happen? Why can't both commands work independently of each other? Is there a workaround for this?

like image 481
Svavinsky Avatar asked Jan 22 '26 09:01

Svavinsky


1 Answers

Because doing .readlines() first will consume all of the read buffer leaving nothing behind for .readline() to fetch from. If you want to go back to the start, use .seek(0) as @abccd already mentioned in his answer.

>>> from StringIO import StringIO
>>> buffer = StringIO('''hi there
... next line
... another line
... 4th line''')
>>> buffer.readline()
'hi there\n'
>>> buffer.readlines()
['next line\n', 'another line\n', '4th line']
>>> buffer.seek(0)
>>> buffer.readlines()
['hi there\n', 'next line\n', 'another line\n', '4th line']
like image 194
shad0w_wa1k3r Avatar answered Jan 25 '26 00:01

shad0w_wa1k3r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!