Use python, no modules can be imported! 1. Write a program called diff.py that a
ID: 3764950 • Letter: U
Question
Use python, no modules can be imported!
1. Write a program called diff.py that asks the user for two files and displays the differences between the characters in each file. 1. Your program should ask the user for the path to two different files 2. For every character that is in the same position in each file but is different between the two files your program should display the index of those characters (starting from 0) as well as the value of those two characters. 3. If one file is longer than the other your program should report the index of each of the characters as well as the fact that it could not find a matching character
4. Examples:
1. Assume ex1.txt contains the contents: batman and ex2.txt contains the contents bitman and ex3.txt contains the contents backmans.
1. Enter the name of the first file: ex1.txt
Enter the name of the second file: ex2.txt
Mismatch at character 1 a != i
2. Enter the name of the first file: ex2.tx
t Enter the name of the second file: ex1.txt
Mismatch at character 1 i != a
3. Enter the name of the first file: ex1.txt
Enter the name of the second file: ex3.txt
Mismatch at character 2 t != c
Mismatch at character 3 m != k
Mismatch at character 4 a != m
Mismatch at character 5 n != a
Mismatch at character 6 != n
No matching character for character 7 (s) found in ex3.txt.
No matching character for character 8 ( ) found in ex3.txt
. 4. Enter the name of the first file: ex3.txt
Enter the name of the second file: ex1.txt
Mismatch at character 2 c != t
Mismatch at character 3 k != m
Mismatch at character 4 m != a
Mismatch at character 5 a != n
Mismatch at character 6 n !=
No matching character for character 7 (s) found in ex3.txt.
No matching character for character 8 ( ) found in ex3.txt.
Explanation / Answer
# save it as diff.py
file1_name=raw_input('Enter the name of the first file: ')
file = open(file1_name, 'r')
x = file.read()
file2_name = raw_input('Enter the name of the second file: ')
file1 = open(file2_name, 'r')
y = file1.read()
for i in range(max(len(y),len(x))):
try:
if x[i]==y[i]:
pass
else:
print 'Mismatch at character %d %s!=%s' % (i,x[i],y[i])
except:
if len(x)>len(y):
print 'No matching character for character %d (%s) found in %s. ' % (i, x[i],file1_name)
else:
print 'No matching character for character %d (%s) found in %s. ' % (i, y[i],file2_name)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.