Using Return In A For Loop
I am making a program that reads through a log file that is stored locally on the C drive. This log file is constantly being updated and my program only prints the new lines of tex
Solution 1:
Use a generator function to produce data as you iterate. Generators can produce data endlessly while you iterate over them:
defread_log_lines(filename):
whileTrue:
# code to read lines if is_new(line):
yield line
This function, when called, returns a generator object. You can then loop over that object like you can over a list, and each time you iterate the code in the generator function will be run until it reaches a yield
statement. At that point the yielded value is returned as the next value for the iteration, and the generator function is paused until you iterate again.
So you'd use it like this:
for new_line in read_log_lines(filename):
# new_line was produced by the generator function
Post a Comment for "Using Return In A For Loop"