比较两个文件
写的比较简单。主要是想要比较每个目录中的文件是否一样。就直接通过dir 遍历出了所有的文件。把他们放入txt中,如果有不一样,我就直接查看,没有的话,就不看了。剩了不少事情。看代码吧,刚学python,写得不好,大家见笑了!
1 #!/usr/bin/env python 2 # coding: utf-8 3 # author: h3i_dan 4 # filename: compare_dir.py 5 # version: v1.0 6 ############################ 7 8 9 import os 10 import sys 11 12 13 def readfile(): 14 15 while True: 16 17 dirve = raw_input('input the directory path(the path or ok): ') 18 if dirve =='': 19 print 'WARNING:\n please input the path!!!' 20 21 elif dirve == 'exit': 22 print 'input enter and exit!!' 23 raw_input() 24 sys.exit() 25 elif dirve == 'ok': 26 compare() 27 raw_input() 28 sys.exit() 29 else: 30 b = 'c:\\todaydir.txt' 31 d = 'dir ' + dirve + ' /s /t /a >>' 32 f = d + b 33 os.system(f) 34 35 def compare(): 36 37 a = 'c:\\originaldir.txt' 38 b = 'c:\\todaydir.txt' 39 40 filename_a = open(a, 'r') 41 filename_b = open(b, 'r') 42 details_a = filename_a.read() 43 details_b = filename_b.read() 44 45 if details_a == details_b: 46 47 print 'ok' 48 49 else: 50 print 'nimei' 51 52 def check_originaldir(): 53 path = 'c:\\originaldir.txt' 54 e = os.path.exists(path) 55 if e == True: 56 check_todaydir() 57 else: 58 print 'WARNING:\n The originadir.txt does not exist!!!' 59 raw_input() 60 61 def check_todaydir(): 62 63 path = 'c:\\todaydir.txt' 64 e = os.path.exists(path) 65 if e == False: 66 readfile() 67 else: 68 print 'WARNING:\n The todaydir.txt already exist!!! ' 69 raw_input() 70 71 if __name__ == '__main__': 72 print '''input exit ---> exit \ninput the path and ok ---> compare dir''' 73 check_originaldir()
但是这样是有弊端的。如果把文件改了之后,大小不变,属性时间也改了。这样就没办法了。不过听说MD5可以做到这一点,过几天写个MD5版本的出来。