1

During the iteration over the text file and over the list I've found the unexpected behavior of for loop. Text file test.txt consists of only two strings: 1) He said: and 2) We said:. First for+for loop

file_ = open('c:\\Python27\\test.txt', 'r')
list_ = ['Alpha','Bravo','Charlie']
try:
    for string in file_:
        for element in list_:
            print string, element
except StandardError:
    print 'Ooops'

returns absolutely expectable result:

He said: Alpha
He said: Bravo
He said: Charlie
We said: Alpha
We said: Bravo
We said: Charlie

But if the for order was changed to

file_ = open('c:\\Python27\\test.txt', 'r')
list_ = ['Alpha','Bravo','Charlie']
try:
    for element in list_:
        for string in file_:
            print string, element
except StandardError:
    print 'Ooops'

the result is totally different:

He said: Alpha
We said: Alpha

Looks like the first for became uniterable. Why?

2 Answers2

3

When you complete the for loop over the file, you "consume" it. You would have to go back to its beginning for each iteration of the outer loop with file_.seek(0). Or use the original loop ordering.

You can replicate the behaviour with this simplified example:

    for string in file_:
        print string

    for string in file_:
        print string

where you'll see the second loop does nothing.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

You need to use file_.seek(0) to return to the beginning of the file in order to re-iterate through its contents.

You have iterated through it via : for string in file_: and so the current position, obtained by calling file_.tell(), will be the size of the file in bytes (if I am not mistaken), signifying the end.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253