noname
noname

Reputation: 1

compare two files in python

in a.txt i have the text(line one after the other)

login;user;name
login;user;name1
login;user

in b.txt i have the text

login;user
login;user
login;user;name2

after comparing it should display in a text file as

login;user;name
login;user;name1
login;user;name2.... 

How can it be done using python?

Upvotes: 0

Views: 972

Answers (3)

tzot
tzot

Reputation: 96081

Based on the vague information given, I would try something like the following:

import itertools

def merger(fni1, fni2):
    "merge two files ignoring 'login;user\n' lines"
    fp1= open(fni1, "r")
    fp2= open(fni2, "r")
    try:
        for line in itertools.chain(fp1, fp2):
            if line != "login;user\n":
                yield line
    finally:
        fp1.close()
        fp2.close()

def merge_to_file(fni1, fni2, fno):
    with open(fno, "w") as fp:
        fp.writelines(merger(fni1, fni2))

The merge_to_file is the function you should use.

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 320049

for a, b in zip(open('a'), open('b')):
    print(a if len(a.split(';')) == 3 else b)

Upvotes: 4

Eli Bendersky
Eli Bendersky

Reputation: 273874

Perhaps the standard-lib difflib module can be of help - check out its documentation. Your question is not clear enough for a more complete answer.

Upvotes: 1

Related Questions