Using python, write code for problem. Two text files are used in this program and i have put screenshot of contents of the file. The text file AllStates.txt contains data from Alabama to Wyoming. The text file FirstStates.txt contains data from Delaware to Rhode Island. Please also put screenshot of your code.
Expert Answer
We can use set operations for the file comparison here. Please find below the Python code for your requirement-
Python code-
with open(‘AllStates.txt’, ‘r’) as file1:
with open(‘FirstStates.txt’, ‘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)
f = open(‘some_output_file.txt’ , ‘r’)
lines = f.readlines()
f.close()
lines.sort()
f = open(‘some_output_file.txt’, ‘w’)
for line in lines:
f.write(line)
f.flush()
f.close()
Screenshot-
I have used sample file 1.txt and 2.txt. Both files have some content and I have subtracted the contents of the two files.
1.txt
2.txt
Code Run window-
Output file