Vagrant Storm Vagrant Storm - 2 months ago 13
Python Question

Any tips on how to get a line number from a text file in python?

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():
for system in systemList:
for resFile in resFilesList:
if os.path.isfile("S:\\KnownGoodOutput\\"+resFile)==True:
with open("S:\\KnownGoodOutput\\"+str(resFile)) as 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 think something like this should work:

fcFile.writelines('{}: {}'.format(line_number, line)
                  for line_number, line in enumerate(tFile)
                  if line not in kSet)