1

When I am doing a while loop, I want my code to go through the same file multiple times:

file = open('anyfile.txt', 'r')
x = 0 
while x<5:
    for line in file:
        #does stuff
    x = x + 1

My code is different, so I have given a simpler piece of code as an example. Whenever I do this, the while loop executes, goes through the file once, and then goes through the while loop till it stops, only going through the file once. How do I get my code to run through the file multiple times? The reason for this is because in my actual code I edit he text file in each loop. Please can someone help?

4
  • you have to rewind your file at each iteration. Commented Feb 13, 2017 at 19:02
  • file is iterator Commented Feb 13, 2017 at 19:02
  • so i basically have to state file = open('anyfile.txt', 'r') after i declare the while loop? Commented Feb 13, 2017 at 19:03
  • You can do that, but then you have to read the file in each time. If it's reasonable to keep the contents in memory, append each line of the file to a list beforehand and iterate through that instead. Commented Feb 13, 2017 at 19:05

3 Answers 3

3

You can use seek to set a file pointer back to the beginning:

file = open('anyfile.txt', 'r')
x = 0 
while x < 5:
    file.seek(0)  # Reset file pointer to start 
    for line in file:
        #does stuff
    x = x + 1
Sign up to request clarification or add additional context in comments.

Comments

1

You can only iterate iterator file once, then it will not yield any more. You can use with open(filename) read the file each time you run through the while loop

while x < 5:
    with open('anyfile.txt') as inputs:
        for line in inputs:
            # do you work here
    x = x +1

1 Comment

Thank you so much, to be honest I was quite dumb to have not noticed the simplicity of my problem, cheers
1

File objects in Python are iterators, once you read until EOF once, the iterator gets exhausted.

You could read the file into a list, so you can iterate on it as many times as is required:

file = open('anyfile.txt', 'r').readlines()
x = 0 
while x < 5:
    for line in file:
        # does stuff
    x = x + 1
file.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.