比较两个文件的不同

import os

def get_file_content(file,path,name):
    if not os.path.isdir(file): #判断是否是文件夹,不是文件夹才打开.
        #print(file,path+"/"+file)
        if os.path.getsize(path+"/"+file):
            with open(path+"/"+file,'r') as f: #打开文件
                n = 0
                for line in f: #遍历文件,一行行遍历,读取文本
                    n += 1
                    print(name,'in')
                      
                    yield [file,line,n]
        else:
            yield [-1,path+"/"+file,-1]
    yield [0,0,0]


path_old = "./old" #文件夹目录
path_new = "./new" #文件夹目录
files_old = os.listdir(path_old) #得到文件夹下的所有文件名称
files_new = os.listdir(path_new) #得到文件夹下的所有文件名称
#print(files_old,files_new)
files_old = set(files_old)
files_new = set(files_new)

new_not_exit = list()
old_not_exit = list()
for each_FileName in files_old:
    if each_FileName in files_new:
        files_new.remove(each_FileName)
    else:
        new_not_exit.append(each_FileName)
        continue
        
    
    old_func = get_file_content(each_FileName,path_old,'old')
    new_func = get_file_content(each_FileName,path_new,'new')

    while True:


        old = old_func.__next__()
        #print('old',old[0],old[2])
        new = new_func.__next__()
        #print('new',new[0],new[2])
        if new[0] == 0:
            break
        elif new[0] == -1:
            print(new[1],'为空文件')

        elif old[0] == -1:
            print(old[1],'为空文件')
        else :
            if old[1] == new[1]:
                continue
            else : 
                print('文件 %s 的第 %d 行不同' % (new[0],new[2]))


print('new文件夹中不存在')
print(new_not_exit)
print('old文件夹中不存在')
print(list(files_new - files_old))

你可能感兴趣的:(比较两个文件的不同)