Get the common values between two text files

Posted on

Problem

I’m just trying to get the common values from two distinct files called file1.txt and file2.txt where I’m using Python’s set method to get the results and this works.

However, I’m looking forward to see if there is better way to do this.

#!/grid/common/pkgs/python/v3.6.1/bin/python3
def common_member():
    a_set = dataset1
    b_set = dataset2
    if (a_set & b_set):
        print(a_set & b_set)
    else:
        print("No common elements")

with open('file1.txt', 'r') as a:
        dataset1 = set(a)
with open('file2.txt', 'r') as b:
    dataset2 = set(b)

common_member()

file1.txt

teraform101
azure233
teraform221
teraform223
teraform224

file2.txt

teraform101
azure109
teraform223
teraform226
teraform225
azure233

Result:

{ 'teraform101n', 'azure233n', 'teraform223n' }

Solution

Global variables (dataset1 and dataset2) are bad. I’d rather see you write no function at all than a function that accepts its inputs through global variables:

with open('file1.txt') as file1, open('file2.txt') as file2:
    print((set(file1) & set(file2)) or "No common elements")

If you do write a function, then it should accept its inputs as parameters. Name the function’s parameters however you want, but avoid unnecessary reassignments like a_set = dataset1 and b_set = dataset2.

def print_common_members(a, b):
    """
    Given two sets, print the intersection, or "No common elements".
    """
    print((a & b) or "No common elements")

with open('file1.txt') as file1, open('file2.txt') as file2:
    dataset1 = set(file1)
    dataset2 = set(file2)
    print_common_members(dataset1, dataset2)

Leave a Reply

Your email address will not be published. Required fields are marked *