简体   繁体   中英

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM