Why is it that only once i am able to use file_object.readlines() and file_object.read() ? After that it is empty

Question:

Code:

f = open("file.txt")

print(f.readlines())

print(f.readlines())
#NOT ABLE TO USE .READLINES TWICE

Output:

['The Gods and the Titans fought over the ruins of Athens.n', 'The Earthling sufferend from these battles.n', "And the French didn't came to help."]
[]

Why is it that after using the first time, the object becomes empty?
The readlines() method returns an empty list.

Asked By: MOHAMMED ASIF KHAN

||

Answers:

From the documentation,

If the end of the file has been reached, f.read() will return an empty string (”).

and

if f.readline() returns an empty string, the end of the file has been reached

The second time you call f.readlines(), it returns an empty list since the file pointer is at the end of the file. If for some reason you need to call f.readlines() a second time, you should use f.seek(0, 0).

Answered By: Rahul
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.