Ehsan
Ehsan

Reputation: 1

Python: Nested For Loops

I have a question I need to ask you. Here is part of my script:

scan=file('indice.txt','r')
for i_L in range(10):
    for line in scan:
        a,b,c=line.split()
        do something ...
        ... ...
    print something
scan.close()

indice.txt is a file containing 3 columns of real numbers.

The main problem is that when the outer loop over i_L executes for the first value of i_L, the loop is broken and only one value is shown in the output.

anyone can help?

Upvotes: 0

Views: 312

Answers (3)

zchenah
zchenah

Reputation: 2108

for line in file:
    ...

is a shorthand for

for line in iter(file.readline, ""):
    ...

So you can see actually it call readline which move the file's current position just as other file operations. It won't go back to the beginning of the file when you iterate again, unless you set the current position manually, like:

yourfile.seek(0)

Also if you don't want to seek from the last position but not from the beginning, 2 "for..in.." is not a good way either, because it may have buffer of it, the right way to this is:

  it = iter(file)
  for line in it:
      if line == "\n":
          break
  for line in it:
      print line,

Please refer to PEP234 for more about this: http://www.python.org/dev/peps/pep-0234/ It explains how different kinds of iterators work. And what happens when you iterate a file.

Upvotes: 0

yosukesabai
yosukesabai

Reputation: 6244

You can also read all line at once into list, and keep using it (assuming this indice.txt is not like 500GB data)

scan=file('indice.txt','r')
lst_scan = list(scan)
scan.close()
for i_L in range(10):
    for line in lst_scan:
        a,b,c=line.split()
        do something ...



        ...
    print something

Upvotes: 1

Adam Zalcman
Adam Zalcman

Reputation: 27233

Before you start looping over the lines in the file again, you should seek the file to the beginning:

scan=file('indice.txt','r')
for i_L in range(10):
    for line in scan:
        a,b,c=line.split()
        do something ...



        ...
    print something
    scan.seek(0)
scan.close()

See file.seek.

You should also consider caching the lines first and then working with the cache.

Upvotes: 3

Related Questions