我有一个名为fileOne的文件.txt如下所示
mystring:
keyFile: enable
clusterAuthMode: enable
authorization: string
transitionToAuth: boolean
javascriptEnabled: enable
redactClientLogData: boolean
security:
keyFile: string
clusterAuthMode: disable
authorization: string
transitionToAuth: boolean
javascriptEnabled: enable
redactClientLogData: boolean
test:
keyFile: disable
clusterAuthMode: enable
authorization: string
transitionToAuth: boolean
javascriptEnabled: enable
redactClientLogData: boolean
stack:
keyFile: string
clusterAuthMode: enable
authorization: string
transitionToAuth: boolean
javascriptEnabled: enable
redactClientLogData: enable
还有一个名为FileTwo 的文件.txt如下所示
security:
keyFile: string
clusterAuthMode: enable
authorization: string
transitionToAuth: boolean
javascriptEnabled: enable
我需要检查FileTwo.txt的上下文是否存在于FileOne中.txt。并打印匹配或不匹配或未找到。
输出 -
Matched - security:
Matched - keyFile: string
NOT Matched - clusterAuthMode: disable
Matched - authorization: string
NOT Matched - FileString: boolean
Matched - javascriptEnabled: enable
NOT Found - redactClientLogData: boolean
代码:
import yaml # pip install pyyaml
def read_yaml(file):
with open(file, 'r') as f:
return yaml.safe_load(f)
def compare(a, b):
for key in a:
if key not in b:
# print('NOT Found - {}'.format(key))
continue
print('Matched - {}'.format(key))
for sub_key, sub_value in a[key].items():
if sub_key not in b[key]:
print('NOT Found - {}: {}'.format(sub_key, sub_value))
else:
if sub_value == b[key][sub_key]:
print('Matched - {}: {}'.format(sub_key, sub_value))
else:
print('NOT Matched - {}: {}'.format(sub_key, sub_value))
f1 = read_yaml('FileOne.txt')
f2 = read_yaml('FileTwo.txt')
compare(f1, f2)
输出:
Matched - security
Matched - keyFile: string
NOT Matched - clusterAuthMode: disable
Matched - authorization: string
Matched - transitionToAuth: boolean
Matched - javascriptEnabled: enable
NOT Found - redactClientLogData: boolean
你提到的txt文件是yaml
格式。如果您不了解yaml,请通过 https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
解析yaml在python中非常容易。 Python附带yaml
模块。您可以使用以下命令安装它,如果您在导入 yaml 模块时遇到导入错误。
pip install pyyaml
一旦你确定安装了yaml模块,那么请使用下面的代码
import yaml
with open("FileOne.txt") as fh:
data1 = yaml.load(fh)
with open("FileTwo.txt") as fh:
data2 = yaml.load(fh)
for key in data2.keys():
if key not in data1.keys():
continue
else:
print "Matched - %s"%(key)
x = data1[key]
y = data2[key]
for k in y:
if k in y and x[k] == y[k]:
print "Matched - %s: %s"%(k, y[k])
else:
print "NOT Matched - %s: %s"%(k, y[k])
我希望这符合您的需求。