简体   繁体   English

两个文件的区别

[英]Differences between two files

I am connecting to a remote machine, and saving the outputs of two queries in two different files and take the results the new results that appear today:我正在连接到远程机器,并将两个查询的输出保存在两个不同的文件中,并将结果作为今天出现的新结果:

Having two files:有两个文件:

yesterday.txt昨天.txt

AAA=1
BBB=2
CCC=3

today.txt今天.txt

AAA=1
BBB=2
DDD=3
EEE=2

The output of the script should be something like this:脚本的输出应该是这样的:

WARNING: DIFFERENCES: DDD=3, EEE=2;

How could I take this difference?我怎么能接受这种差异?

I have tried with the "diff" command from my Python script, but it seems like it is buggy...我已经尝试使用 Python 脚本中的“diff”命令,但它似乎有问题......

Use the Difflib library:使用Difflib库:

from difflib import Differ

# AAA=1
# BBB=2
# CCC=3
with open("yeterday.txt","r") as f1:
    text1 = f1.read()

# AAA=1
# BBB=2
# DDD=3
# EEE=2
with open("today.txt","r") as f2:
    text2 = f2.read()


d = Differ()
result = list(d.compare(text1, text2))


#   A  A  A  =  1  
#   B  B  B  =  2  
# - C- C- C+ D+ D+ D  =  3+ 
# + E+ E+ E+ =+ 2
print(''.join(result))

# Printing the desired message if difference was detected
output_list = ''.join([diff_char.replace('+ ', '').replace(' +', '') for diff_char in difflib.ndiff(text1, text2) if '+' in diff_char[0]])

if output_list:
    # WARNING: DIFFERENCES:
    # DDD
    # EEE=2
    print(f'WARNING: DIFFERENCES:\n{output_list}')

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

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