Python Input/Output Idioms

Unlike the C programming language, Python assignments are statements, not expressions. Therefore the common C idiom of:

while (line = fgets(f)) {
    /* do something with the line */

is not possible to implement directly.

However, provides several alternatives using iterators or the while True idiom. I recently discovered the built-in iter() function as well:

for line in iter(f.readline, "END"):
    ... do something with line ...

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>