首页 > 解决方案 > 用 Python 比较两个 linux 组文件

问题描述

我需要将两个 Linux 组文件与 Python 进行比较,并在组中找到一个丢失的用户。我使用了下面的代码,但如果用户的顺序不同,它就会失败。

with open('group1', 'r') as file1:
    with open('group2', 'r') as file2:
        same = set(file1).difference(file2)

same.discard('\n')

with open('some_output_file.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

例如,

group1:
test:x:1234:mike,john,scott
test2:x:1234:mike,john
test3:x:1234:tim,dustin,Alex

group2:
test:x:1234:mike,scott,john
test2:x:1234:mike,john,scott
test3:x:1234:dustin,tim

理想的输出是

missing group1:
test2:scott

missing group2:
test3:Alex

我应该拿每个用户进行比较吗?比较两个文件的最佳方法是什么?

标签: python

解决方案


这应该有效:

def create_dict_from_file(filename):
    """Read one file and extract from it the group name put as key and the user
    in it as values"""
    with open(filename, 'r') as file1:
        all_groups = file1.read().split('\n')
    return {
        one_line.split(':')[0]: one_line.split(':')[-1].split(',')
        for one_line in all_groups
    }


def create_missing_element(reference, other, key):
    """Create a dict with the missing elements if it exists"""
    missing_in_reference = set(reference) - set(other)
    if missing_in_reference:
        return {key: missing_in_reference}
    return {}


file_1_groups = create_dict_from_file('group1')
file_2_groups = create_dict_from_file('group2')

all_missing_group1 = {}
all_missing_group2 = {}
for key in file_1_groups:
    all_missing_group1.update(
        create_missing_element(file_1_groups[key], file_2_groups[key], key)
    )
    all_missing_group2.update(
        create_missing_element(file_2_groups[key], file_1_groups[key], key)
    )

print (all_missing_group1)
print (all_missing_group2)

我让你把结果写在一个文件里。

set是一种 Python 结构,您不能在其中重复且易于操作以查找丢失的元素

我使用字典理解来创建字典,其中组名作为键(使用 拆分时行中的第一个元素:)和用户作为值(使用 拆分时行中的最后一个元素:)。用户值再次使用,as 分隔符拆分,以便将用户作为一个列表,可以在 Python 中轻松处理。


推荐阅读