user3494047
user3494047

Reputation: 1693

In python how to have two file iterators iterating over lines at different rates?

I have seen lots of questions and answers similar to Iterating over two text files in python

This is not what I want.

I want to do something like:

with open(file_1) as in_file_1:
    with open(file_2) as in_file_2:
        cur_line_1 = file_1.nextLine()
        cur_line_2 = file_2.nextLine()
        while(some_while_condition(cur_line_1)):
            if some_condition(cur_line_1):
                cur_line_2 = file_2.nextLine()
                print(some_func(cur_line_1, cur_line_2))
            cur_line_1 = file_1.nextLine()

Upvotes: 2

Views: 74

Answers (1)

Nullman
Nullman

Reputation: 4279

You almost got it, instead of nextLine do readline
you can also combine both with statements:

with open(file_1) as in_file_1, open(file_2) as in_file_2:
    cur_line_1 = file_1.readline()
    cur_line_2 = file_2.readline()
    while(some_while_condition(cur_line_1)):
        if some_condition(cur_line_1):
            cur_line_2 = file_2.readline()
            print(some_func(cur_line_1, cur_line_2))
        cur_line_1 = file_1.readline()

Upvotes: 1

Related Questions