0

I have two txt files. I want to merge those files using python. I just began to study python and need some help. I tried searching google to resolve this resolved this but I can't find solution.

So please help me.

Below are my two txt file.

a.txt has this data.

Zone,alias1,alias2
PA1_H1,PA1,H1
PA2_H2,PA2,H2

b.txt has this data.

WWN,Port,Aliases
da,0,PA1
dq,1,PA2
d2,3,H1
d4,1,H2

Expected Output

Zone,alias1,WWN,Port,alias2,WWN,Port
PA1_H1,PA1,da,0,H1,d2,3
PA2_H2,PA2,dq,1,H2,d4,1

I tried below script but I can't merge.

row = []
for line in open("mod_alias.txt"):
        line = line.split(',')[2]
        row.append(line)

strings = row

for line in open("mod_all_cfgshow.txt"):
        if any(s in line for s in strings):
                field1,field2,field3 = line.split(',')
                print field1,field2,field3

How can I merge file? Could you show me example?

1
  • 1
    What is the criteria for merging? Based on which column?
    – Rohan
    Jul 31, 2017 at 16:58

2 Answers 2

1

Here's some code to get you started. This code will show you how to open both files and combine them. Then, all you'll need to do is modify the code to merge the files using whichever specific rules you'd like.

    # Open Files, read data to lists, and strip data

    with open("b.txt") as bFile:
            bContent = bFile.readlines()
            bContent = [line.strip() for line in bContent]


    with open('a.txt') as aFile:
            aContent = aFile.readlines()
            aContent = [line.strip() for line in aContent]

    # Create a file to store the merged text

    m = open('merged.txt','w')

    # Cycle through the text read from files and merge, and then print to file
    for aLine, bLine in zip(aContent, bContent):

            mergedString = aLine+','+bLine
            print>>m,mergedString
0

This should get you started

import csv

# read all the data in b.txt into a dictionary, key'd by the alias. We'll look this up later
data = {}
with open("b.txt") as infile:
    for row in csv.DictReader(infile):
        alias = row["Aliases"]
        data[alias] = row

with open("a.txt") as fin, open("output.txt", 'w') as fout:
    infile = csv.DictReader(fin)
    outfile = csv.DictWriter(headers=infile.headers+data.keys())
    for row in infile:
        row.update(data[row["Aliases"]]) # update the row with the data from b.txt
        outfile.writerow(row)
1
  • Thank you so much. But your script have error. Traceback (most recent call last): File "test7.py", line 12, in <module> outfile = csv.DictWriter(headers=infile.headers+data.keys()) AttributeError: DictReader instance has no attribute 'headers'
    – KJ9
    Jul 31, 2017 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.