I want to search two files to find the missing values when compared to each other.
context = each file has ~200 single word lines.
This code works but..., is there a more efficient way to code this to achieve the same results? ** The output doesn't need to look identical, I just want to differentiate which file the differences exist in.
file1 = open('python3.9', 'r').readlines() # text file
file2 = open('python3.8', 'r').readlines() # text file
print(10 * '-', 'file python3.8 is missing', 10 * '-') # format for readability
for line in file1:
if line not in file2:
print(line, end='')
print(10 * '-', 'file python3.9 is missing', 10 * '-') # format for readability
for line in file2:
if line not in file1:
print(line, end='')
print('\n',10 * '-', 'Done', 10 * '-') # code completion confirmation
output...
---------- file python3.8 is missing ----------
_aix_support.py
_bootsubprocess.py
graphlib.py
zoneinfo
---------- file python3.9 is missing ----------
_dummy_thread.py
config-3.8-x86_64-linux-gnu
dummy_threading.py
---------- Done ----------
CodePudding user response:
you can use list comprehensions,
result_1 = list((line for line in file1 if line not in file2))
result_2 = list((line for line in file2 if line not in file1))