0

I made up a quick file compare tool that will check for the differences between two files. I suddenly realized I probably will need the line number the difference occurs at. Any one have any tips on how I should incorporate that into the following code?

def fileCompare():
    systemList=os.listdir("S:\\Automation_Results")
    for system in systemList:
        resFilesList=os.listdir("S:\\Automation_Results\\"+system)
        for resFile in resFilesList:
            if os.path.isfile("S:\\KnownGoodOutput\\"+resFile)==True:
                with open("S:\\KnownGoodOutput\\"+str(resFile)) as kFile:
                    kSet=set(kFile)
                    with open("S:\\Automation_Results\\"+str(system)+"\\"+str(resFile)) as tFile, open("S:\\FC_Result_Files\\Compare_Results for"+str(system)+".txt","w") as fcFile:
                         fcFile.writelines(line for line in tFile if line not in kSet)

I was thinking I would probably have to increment a counter as the lines are read, but believe I'd need to redo my compare method for that though I hope I am wrong as I rather like this method...runs really well.

I do not see how my question is a duplicate to what was linked. Here I am getting line number in a file when a mismatch occurs between two compared files. In the link they are just getting the total line numbers in a file. Yes, some of the answers use enumerate, but not in this manner. If I wanted to just count lines...well...I wouldn't have been asking. This link has more in common with what I am doing, but since it on a different topic searching it up would have been very unlikely plus it is still a completely different use case.

Community
  • 1
  • 1

1 Answers1

0

I think something like this should work:

fcFile.writelines('{}: {}'.format(line_number, line)
                  for line_number, line in enumerate(tFile)
                  if line not in kSet)
user94559
  • 59,196
  • 6
  • 103
  • 103
  • Ahh...I completely forgot about enumerate...though in my defense file manipulation isn't what I am typically using Python for. Though for any future viewers you will want to set the start of the enumerate...in my case I just need to change ...enumerate(tFile,start=1) or else my line numbers will be one off. Thanks a million – Vagrant Storm Nov 02 '16 at 03:51
  • Something else has come up on this. I need to capture the value of line_number. I want to use it has a variable elsewhere. I am trying to use it to print the line of the file that the result file is being compared against. I put the file in a list and then I am trying: fcFile.writelines('{}: {}'.format(line_number, line, kLines[line_number])... and it is giving me a index out of range because line_number apparently has no value even though it prints perfectly fine in the output file. – Vagrant Storm Dec 09 '16 at 22:23
  • @VagrantStorm Ask a new question and include your current code. – user94559 Dec 10 '16 at 02:13