Home > Net >  Trying to compare 2 text files, getting" IndexError: list index out of range" error
Trying to compare 2 text files, getting" IndexError: list index out of range" error

Time:11-15

I have a school assignment: "This program should prompt the user for the names of two text 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” to the console. If they are not, the script should output “No”, followed by the first lines 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. "

The text files are given to us with the comment "The links below contain text for testing. Text1 and Text2 are the same file, Text3 is slightly different. "

I am getting an error when I run the program, saying if f1lines[lineCount] != f2lines[lineCount]:

IndexError: list index out of range

What am I doing wrong?

file1 = input("Enter name of first file to compare: ")
file2 = input("Enter name of second file to compare: ")

f1 = open(file1, 'r')
f2 = open(file2, 'r')

f1lines = f1.readlines()
f1.close()
f2lines = f2.readlines()
f2.close()

def compare_lines():
    lineCount = 0

while lineCount != len(f1lines):

    if f1lines[lineCount] == f2lines[lineCount]:
        lineCount  = 1
        if lineCount == len(f1lines):
            print("Yes")
    if f1lines[lineCount] != f2lines[lineCount]:
        print("No")
        print(f2lines[lineCount])

CodePudding user response:

change if to elif

elif f1lines[lineCount] != f2lines[lineCount]:
    print("No")
    print(f2lines[lineCount])
    break

CodePudding user response:

No need to write this much code it is much easier with this code. You may try it

   file1 = input("Enter name of first file to compare: ")
   file2 = input("Enter name of second file to compare: ")

   f1 = open(file1, 'r')
   f2 = open(file2, 'r')

   f1lines = f1.readlines()
   f1.close()
   f2lines = f2.readlines()
   f2.close()

   if len(f1lines) == len(f2lines):
      print(Yes)
   else:
      print("No)
  • Related