简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM