MKS
MKS

Reputation: 199

Why nested for loop is not working Python?

The outer foor loop is executing onl one time. I can not detect the problem why this is happeding?

f=open("simpletextfile.txt")
for r in range(1,52):
    for line in f.readlines():
        print r

where simpletextfile.txt contains the message This a message!!.

Upvotes: 0

Views: 100

Answers (3)

Hiadore
Hiadore

Reputation: 714

When you call f.readlines() for first time, it will return a list with one item: ['This a message!!']. But when you call f.readlines() for the second time and so on it will return empty list []. So, when you loop over it, it will not looping at all because the list is empty. Assign f.readlines() to variable to fix your problem

f = open("simpletextfile.txt")
for r in range(1,52):
    lines = f.readlines()
    for line in lines:
        print r

Upvotes: 1

modesitt
modesitt

Reputation: 7210

The file is exhausted after you call readlines, as in subsequent calls to readlines will not read more lines as all the lines have been read. The inner loop with then execute but have nothing to do. If you want to read the lines 52 times and print r (I do not know why - but ok), do the following

with open('simpletextfile.txt') as f:
    lines = f.readlines()
    for r in range(1, 52):
        for line in lines:
            print r

Furthermore, although you are only reading the file in this example (and Python will close it automatically for you), you should explicitly .close() it yourself or wrap it around a with statement as above, which will close it at the end - it is less sloppy.

Upvotes: 3

Aule Mahal
Aule Mahal

Reputation: 708

Because you can't read a text file twice. So on the first iteration, it reads the file and prints "1" as many times as they are lines in your file. When it goes to r==2, it tries to call f.readlines(), but as the file is already read, it stops the iteration before even starting it. And so on up to r == 51.

If you explain more what you're trying to do, we can maybe help more effectively.

Upvotes: 4

Related Questions