Categories
Python Answers

How to fix iterating on a file doesn’t work the second time with Python?

Spread the love

Sometimes, we want to fix iterating on a file doesn’t work the second time with Python.

In this article, we’ll look at how to fix iterating on a file doesn’t work the second time with Python.

How to fix iterating on a file doesn’t work the second time with Python?

To fix iterating on a file doesn’t work the second time with Python, we can use the with keyword.

For instance, we write

with open('foo.html', 'rU') as f:
  for line in f:
     print(line)

to open foo.html.

Then we loop through the lines in the file in the for loop.

Once the loop is done, the file is closed so that we can open it again and run the loop on it again.

Conclusion

To fix iterating on a file doesn’t work the second time with Python, we can use the with keyword.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *