Koloktos Koloktos - 3 years ago 86
Python Question

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?

Answer Source

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:


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

[32]Apple Banana Orange

Blue Red [32] Green Black
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download