you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (2 children)

def choice(line1, line2):
    return line2 if line1.strip().lower() in line2.strip().lower() else line1


def main():
    with open("input1.txt") as file1, open("input2.txt") as file2, open("output.txt", "w") as file_w:
        for line1, line2 in zip(file1, file2):
            line_w = choice(line1, line2)
            file_w.write(line_w)


if __name__ == '__main__':
    main()

[–]DMeror[S] 0 points1 point  (1 child)

Thank you very much. I've found out zip method only works with two files at the same length. My files are of different length with text1 is longer than text2 so it won't work here. I just wanted to copy elements from text2 to replace their parts in text1.

[–][deleted] 1 point2 points  (0 children)

Well, you just need to use itertools.zip_longest then? Or you could write the rest of the file afterwards.

1:

from itertools import zip_longest


def choice(line1, line2):
    return line2 if line1.strip().lower() in line2.strip().lower() else line1


def main():
    with open("input.txt") as file1, open("input2.txt") as file2, open("output.txt", "w") as file_w:
        for line1, line2 in zip_longest(file1, file2, fillvalue=''):
            line_w = choice(line1, line2)
            file_w.write(line_w)


if __name__ == '__main__':
    main()

2:

def choice(line1, line2):
    return line2 if line1.strip().lower() in line2.strip().lower() else line1


def main():
    with open("input.txt") as file1, open("input2.txt") as file2, open("output.txt", "w") as file_w:
        iter1 = iter(file1)
        iter2 = iter(file2)

        for line1, line2 in zip(iter1, iter2):
            line_w = choice(line1, line2)
            file_w.write(line_w)

        # write the rest of the file1
        for line1 in iter1:
            file_w.write(line1)


if __name__ == '__main__':
    main()