with open('some_file_1.txt', 'r') as file1: with open('some_file_2.txt', 'r') as file2: same = set(file1).intersection(file2) same.discard('\n') with open('some_output_file.txt', 'w') as file_out: for line in same: file_out.write(line)
Here is what the above code is Doing:
1. Open the first file in read mode and store its data in the file1 variable.
2. Open the second file in read mode and store its data in the file2 variable.
3. Use the set.intersection() method to find the common lines between file1 and file2.
4. Use the set.discard() method to remove the newline character (‘\n’) from the set.
5. Open a new file in write mode and store its data in the file_out variable.
6. Use a for loop to iterate over the set and write each line to the new file.