Get the common values between two text files

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:

{ 'teraform101\n', 'azure233\n', 'teraform223\n' }


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)

• This is indeed a great answer. – Karn Kumar Sep 6 '18 at 19:08
• in case we need the resulting values into a new line , how could we do that into this code itself – Karn Kumar Sep 6 '18 at 19:12
• @newTOcode: Assign common_members = a & b and then do with that variable whatever you want. – Graipher Sep 7 '18 at 8:00
• @Graipher, thnx for your valuable inputs, its solved with using join method as print('\n'.join(s.strip('\n') for s in a & b) or "No common element") – Karn Kumar Sep 7 '18 at 8:03