Python Generator Functions Not Just For Loops

Examples I see for Python generators always seem to involve a for loop, but that may not always be want you want to do. For example, if you want to compare two .csv files, you could do something like this, as a starting place at least.

import csv

def csv_lazy_get(csvfile):
    with open(csvfile) as f:
        r = csv.reader(f)
        for row in r:
            yield row

def csv_cmp_lazy(csvfile1, csvfile2):
    gen_2 = csv_lazy_get(csvfile2)

    for row_1 in csv_lazy_get(csvfile1):
        row_2 =

        print("row_1: ", row_1)
        print("row_2: ", row_2)

        if row_2 == row_1:
            print("row_1 is equal to row_2.")
            print("row_1 is not equal to row_2.")


Leave a comment

Filed under python

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s