Computer Science, asked by rahulrajspc5332, 7 months ago

Write a program named dif.py. This script should prompt the user for the names of two test files and compare the contents of the two files to see if they are the same. If they are, the program should simply output "YES". If they are not, the program should output "NO", followed by the first line of each file that differ from each other. The input loop should read and compare lines from each file. The loop should break as soon as a pair of different lines is found.

Answers

Answered by ayeshaukaye04
0

Answer:

a=b=True

f1=open('file1.txt')

f2=open('file2.txt')

while a or b:

     a=f1.readline()

     b=f2.readline()

     if a!=b:

          print('NO')

          print('from file1:', '/n', a)

          print('from file2:' , '/n', b)

          break

else:

     print('YES')          

f1.close()

f2.close()      

Answered by poojan
1

Comparison of the contents between two text files using the 'Python File Concept'.

Language used: Python Programming

Program:

f1=open(input('Enter the name of the first file: '),'r')

f2=open(input('Enter the name of the second file: '),'r')

flag=0

for l1, l2 in zip(f1,f2):

   if l1!=l2:

       flag=1

       print("NO")

       print("Mismatch at: ")

       print("Line in file1: ", l1, end="")

       print("Line in file2: ", l2)

       break

if flag==0:

   print("YES")

Output:

Enter the name of the first file: a.txt

Enter the name of the second file: b.txt

NO

Mismatch at:  

Line in file1:  Hope you are fine.

Line in file2:  Hope u are fine.

Explanation:

  • First, read the two files into the corresponding variables, by taking the file names from the user dynamically. Take a flag value.
  • zip() pairs the objects taken in each iteration. Send f1, f2 as its parameters such that it pairs up each line of the two files and once entered into the loop, checks whether they are equal or not.
  • If they aren't equal, change the flag value and print a statement that states 'NO' along with the statements where the difference can be found, and then break the loop.
  • If all the statements in the two files are equal, the flag value never changes. So, check the flag value. If it is the same as the first initialized one, print 'YES'.

Learn more:

  • Printing all the palindromes formed by a palindrome word.

        brainly.in/question/19151384

  • Raju has a square-shaped puzzle made up of small square pieces containing numbers on them. He wants to rearrange...

       https://brainly.in/question/16956126

Attachments:
Similar questions