Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the second time I run "readlines" on the same file nothing is returned?

Tags:

python

>>> f = open('/tmp/version.txt', 'r')
>>> f
<open file '/tmp/version.txt', mode 'r' at 0xb788e2e0>
>>> f.readlines()
['2.3.4\n']
>>> f.readlines()
[]
>>>

I've tried this in Python's interpreter. Why does this happen?

like image 612
Somebody still uses you MS-DOS Avatar asked Aug 19 '10 17:08

Somebody still uses you MS-DOS


People also ask

What will some file Readlines () return?

The readlines() method returns a list containing each line in the file as a list item.

Does Readlines read entire file?

The readlines method returns the contents of the entire file as a list of strings, where each item in the list represents one line of the file. It is also possible to read the entire file into a single string with read .

Does Readlines return string?

readlines doesn't return strings. It returns a list of some number of strings.


2 Answers

You need to seek to the beginning of the file. Use f.seek(0) to return to the begining:

>>> f = open('/tmp/version.txt', 'r')
>>> f
<open file '/tmp/version.txt', mode 'r' at 0xb788e2e0>
>>> f.readlines()
['2.3.4\n']
>>> f.seek(0)
>>> f.readlines()
['2.3.4\n']
>>>
like image 157
sberry Avatar answered Nov 15 '22 09:11

sberry


Python keeps track of where you are in the file. When you're at the end, it doesn't automatically roll back over. Try f.seek(0).

like image 41
Alex Bliskovsky Avatar answered Nov 15 '22 09:11

Alex Bliskovsky