2013年8月25日

Python Simple File Compare

import sys
from Tkinter import *
from ScrolledText import ScrolledText

def fc(fn1, fn2):
  f = open(fn1, "rU")
  d1 = f.readlines()
  f.close();
  f = open(fn2, "rU")
  d2 = f.readlines()
  f.close();

  for i in range(len(d1)):
    d1[i] = d1[i].replace(' ', '_')
  for i in range(len(d2)):
    d2[i] = d2[i].replace(' ', '_')

  root = Tk()
  root.title('File Compare')
  
  txt = ScrolledText(root, undo=True)
  txt.pack(padx = 5, pady = 5, expand=True, fill='both')
  txt.configure(background='light goldenrod')

  diff = False
  for i in range(max(len(d1), len(d2))):
    if len(d1) > i and len(d2) > i:
      if d1[i] != d2[i]:
        diff = True
        txt.insert(INSERT, "L%03d" % (i + 1) + ':' + d1[i])
        txt.insert(INSERT, '---->' + d2[i])
    elif len(d1) > len(d2):
      diff = True
      txt.insert(INSERT, "L%03d" % (i + 1) + ':' + d1[i])
      txt.insert(INSERT, '---->No answer\n')
    else:
      diff = True
      txt.insert(INSERT, 'No output\n')
      txt.insert(INSERT, '---->' + d2[i])
  if diff:
    txt.configure(foreground='red')
  else:
    txt.insert(INSERT, 'No difference\n')
  root.mainloop()

def main():
  if len(sys.argv) < 3:
    fc("out.txt", "ans.txt")
  else:
    fc(sys.argv[1], sys.argv[2])

if __name__ == '__main__':
  main()

沒有留言:

張貼留言