简体   繁体   English

比较python中的两个文件

[英]compare two files in python

in a.txt i have the text(line one after the other) 在a.txt中,我有文字(一个接一个)

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

in b.txt i have the text 在b.txt中,我有文字

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? 如何使用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. 也许standard-lib difflib模块可以提供帮助-查阅其文档。 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. merge_to_file是您应该使用的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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