Search notes:

Python: using iter() and open()

The following simple example tries to demonstrate how the built-in functions iter() and open() might be used to iterate over each line of a file:
#!/usr/bin/python3

with open('iter.txt') as txt:
     for line in iter(txt.readline, ''):
       # Remove trailing new line because…
         line = line.rstrip('\n')
       # … it is implicitely added in print()
         print(line)
Github repository about-python, path: /built-in/functions/open/iter.py

See also

This page might have a more natural way to iterate over lines in a file.

Index