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.