Reputation: 111
sample.txt:
sample string
code:
temp = open("sample.txt", "r") for i in range(0, 4): text = temp.read() print(text)
output:
sample string
Why does using read() in loop prevent another 4 cycles?
Upvotes: 0
Views: 1784
Reputation: 1538
The first call to the read
method actually returns all the content of the file.
If I understand correctly, you're trying to read the first 4 lines of your file.
You should either do this by iterating through the file and breaking after 4 lines have been read or simply using readline
instead of read
Here's how you could do it with readline
temp = open("sample.txt", "r")
for i in range(0, 4):
text = temp.readline()
print(text)
Check "Methods on File Objects" in the doc for more info about what methods you can use.
If you were trying to read the whole file's content 4 times, then just put your call to the read
method before the loop:
temp = open("sample.txt", "r")
text = temp.read()
for i in range(0, 4):
print(text)
Upvotes: 0
Reputation: 82600
This is because once you run read
on a file, it reaches the EOF or the End of File, and thus cannot give you any more text. So, it just gives you an empty string
So let me demonstrate with an example:
temp = open('text.txt')
for i in range(4):
print("Iteration @ {}".format(i))
t = temp.read()
print(t)
With text.txt
containing:
hello world
cheese cakes
You would get this result:
Iteration @ 0
hello world
cheese cakes
Iteration @ 1
Iteration @ 2
Iteration @ 3
Upvotes: 1
Reputation: 721
user2309239 is right: read() without parameters read everything(well, the buffer) so after the first read, the cursor is at EOF. And there is nothing to read anymore. I think you want temp.read(1), or be more specific with the question. EDIT: move the read to while instead of for, if you want a break at the end of reading.
Upvotes: 0
Reputation: 5048
this can do what you want, I suppose:
for i in range(0, 4):
with open("sample.txt", "r") as temp:
text = temp.read()
print(text)
Upvotes: 0
Reputation: 10288
As doc says:
If the end of the file has been reached, f.read() will return an empty string ("").
So the end of the files has been reached in the first iteration and then it is returning the empty string.
Check the documentation of method of file objects
Upvotes: 2