0

I have a file "file.csv" with this code:

AAA;aaa
BBB;bbb
CCC;ccc

I have a script "program.py" with this code:

temp = open("file.csv", "rt")
for X in temp:
    print("loop_1")
    for Y in temp:
        print("     loop_2")
temp.close()

And I have this result:

loop_1
     loop_2
     loop_2

But I wish I had this:

loop_1
     loop_2
     loop_2
     loop_2
loop_1
     loop_2
     loop_2
     loop_2
loop_1
     loop_2
     loop_2
     loop_2

I don't understand the program's output.

I tried a loop inside another loop, but the result doesn't match with my expectation.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • The inner loop is reading everything in the file. So when the outer loop repeats, there's nothing left to read. Either put `temp.seek(0)` before the inner loop, or read everything into a list and loop through that. – Barmar Nov 21 '22 at 08:41
  • The outer loop reads the first line; then the inner loop reads the second, and the third line; now the file has reached the end, so both loops terminate – gimix Nov 21 '22 at 08:41

0 Answers0