开发者

compare two files in python

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

login;user;name
logi开发者_如何学Cn;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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜