1

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?

Taku
  • 31,927
  • 11
  • 74
  • 85
Svavinsky
  • 69
  • 3
  • 2
    Readlines reads all of the lines, so there is nothing left to read unless you seek back to the beginning of the file. – Random Davis Apr 14 '17 at 19:15

3 Answers3

4

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']
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
3

Because readlines read all the lines in the file, so there's no more lines left to read, to read the file again, you can use f.seek(0) to go back to the beginning and read from there.

Taku
  • 31,927
  • 11
  • 74
  • 85
1

Files have a byte offset which is updated whenever you read or write them. This will do what you initially expected:

with open("file.txt") as f:
    a = f.readlines()
    f.seek(0)  # seek to the beginning of the file
    b = f.readline()

Now a is all the lines and b is just the first line.

U2EF1
  • 12,907
  • 3
  • 35
  • 37