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.
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)
.
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.
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)
.