0

I have a quick question about the readlines() method for file objects in Python.

I have a file (file1.txt) containing the following:

one
two
three
four
five

I know I can use readlines() on this file in the interpreter like so:

>>>f = open('file1.txt', 'r+')
>>>f.readlines()
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']

Similarly, I can do this:

>>>f = open('file1.txt', 'r+')
>>>lines = f.readlines()
>>>lines
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']

However, it seems like I can only run the readlines() method once:

>>>f = open('file1.txt', 'r+')
>>>f.readlines()
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
>>>lines = f.readlines()
>>>lines
[]

What is going on here? Why does f.readlines() return an empty list the second time I call it?

Thanks.

detroitwilly
  • 811
  • 3
  • 16
  • 30

1 Answers1

1

When you read the file once, the file pointer have moved to the end of the file, you have to call f.seek(0) to move the file pointer back to the start.

shellfly
  • 892
  • 2
  • 13
  • 20