0

I am a Python beginner and was troubleshooting a bigger project of mine in a smaller, separate file. The problem with my bigger project was that I could not get two for loops to work consecutively.

I have a txt file containing two lines

The code is simple:

file=open("test.txt","r")
for line in file:
    print("x")
    pass
print("hi") 
for line in file:
    print("x")

The two for loops are identical bar pass.

print("hi") exists as a means of checking if the first for loop is broken out of (which it is)

This code outputs:

x
x
x
hi

The first for loop is broken out of and the print statement works after it, but the for loop after that doesn't? I would have expected it to output:

x
x
x
hi
x
x
x

How can I fix this?

Thanks

Syno
  • 3
  • 2

1 Answers1

5

The problem is that in your first loop, you will reach EOF (end-of-file) when the loop ends, so any subsequent loops over it will not have anything to read, you can use readlines to get a list of lines that you can loop over as much as you want:

with open("test.txt", "r") as f:  #  use `with` to automatically close the file after reading
    lines = f.readlines()

for line in lines:
    print("x")
    #pass `unnecessary`
print("hi") 
for line in lines:
    print("x")

Alternatively (for huge files), you can use seek to get the reader back to the start of the file:

file = open("test.txt", "r")

for line in file:
    print("x")

print("hi")
file.seek(0)

for line in file:
    print("x")

file.close()
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55