[Solved] One-liner for calling a function for each line in a file [closed]


Well, almost in one line (if you allow me to import the itertools module):

[ x for x in itertools.takewhile(
    lambda line: sync(line) == 0,    # <- predicate
    open("file.txt")) ]              # <- iterable

Example w/o file:

>>> import itertools
>>> def sync(n):
...   if n == 3: return -1 # error
...   return 0

>>> lines = [1, 2, 3, 4, 5, 6]
>>> [ x for x in itertools.takewhile(lambda x: sync(x) == 0, lines) ]
[1, 2]

But you really should not obscure things, so why not just:

with open("file") as fh:
    for line in fh:
        if not sync(int(line)) == 0:
            break

solved One-liner for calling a function for each line in a file [closed]