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

0

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

For big files, storing the lines in a list is not a good idea at all.
@Bhawan file.seek will solve this.
That could not have made more sense, cheers MrGeek

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.