Koloktos
Koloktos

Reputation: 123

Reading two text files and copying text from one file to other given satisfied condition

I have two text files, A.txt and B.txt.
Each line in A.txt is of the following form:

[Num]WordA1 WordA2 WordA3

Each line in B.txt is of the following form:

WordB1 WordB2 [Num] WordB3 WordB4

The idea is I want to find the lines in A.txt that contain the same [Num] as some line in B.txt and add the string in the fourth column of that line in B.txt to the second column of the associated line in A.txt. For example, say A.txt contains

[32]Apple Banana Orange
[73]Kiwi Grape Lemon

And B.txt contains

Blue Red [32] Green Black
Red White [105] Purple Green
Brown Pink [73] Blue Black

I would want the output (so, in A.txt) to be:

[32]Apple Green Banana Orange
[73]Kiwi Blue Grape Lemon

So to generalize, how do I match lines across two text files based on a string in a specified position and add another string in one of the matched lines to the other line, in a specified position?

Upvotes: 1

Views: 70

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15236

Here is how I would do this with regular expression.

First we open each file.

Then we compare the values of each row inside of the [] brackets.

Once we find a match we can print each line.

import re

file_a = open("./A.txt", "r")

file_b = open("./B.txt", "r")

for a_line in file_a:
    a = re.findall(r"([0-9]+)", a_line)

    for b_line in file_b:
        b = re.findall(r"([0-9]+)", b_line)
        if a == b:
            print(a_line)
            print(b_line)

    file_b.seek(0)

file_a.close()
file_b.close()

The results with the date you gave as an example look like this:

[32]Apple Banana Orange

Blue Red [32] Green Black

[73]Kiwi Grape Lemon
Brown Pink [73] Blue Black

Upvotes: 1

Related Questions