python文件對比利用difflib庫實現文件夾下詳細內容對比


使用difflib庫和hashlib來對比篩選文件,兩個文件md5相同說明文件沒有變動,然后利用difflib方法實現文件對比,最終生成報告

# -*- coding: utf-8 -*-
__author__ = "Lee.le"
import sys, time
import hashlib
import difflib
import os
from multiprocessing import Pool,Queue

_print = print


def print(*args, **kwargs):
    _print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), *args, **kwargs)


def read_file(filename):
    """
    讀取文件
    :param filename:
    :return:
    """
    try:
        with open(filename, 'r', encoding='UTF-8') as f:
            return f.readlines()
    except IOError:
        print(f"ERROR: 沒有找到文件:{filename}或讀取文件失敗!")
        sys.exit(1)


def compare_file(file_old, file_new):
    """
    對比兩個文件的差異
    :param file_old: 第一個文件
    :param file_new: 第二個文件
    :return:
    """
    name = file_old.split('\\')[-1]
    path = os.path.abspath(os.getcwd())
    out_file = f'{path}\\result\\{name}.html'
    print(f'開始對比-------{name}')
    file1_content = read_file(file_old)
    file2_content = read_file(file_new)
    d = difflib.HtmlDiff()
    result = d.make_file(file1_content, file2_content)
    with open(out_file, 'w', encoding='UTF-8') as f:
        f.writelines(result)
    print(f'完成對比-------{name}')


def file_check(path, i):
    """
    文件篩選
    :param path: 路徑
    :param i: 路徑標識,用於區分兩個文件的返回內容
    :return:
    """
    dir_list = os.listdir(path)  # 返回包含目錄中文件名的列表
    temp_old = []  # 定義一個列表,用來存儲文件路徑
    temp_new = []
    for file in range(len(dir_list)):
        if '.txt.meta' not in dir_list[file]:
            if i == 0:
                temp_old.append(dir_list[file])
            elif i == 1:
                temp_new.append(dir_list[file])
    if i == 0:
        return temp_old
    elif i == 1:
        return temp_new


def md5_check(file_old, file_new):
    """
    md5檢查,過濾沒有變動的文件
    :param file_old: 第一個文件
    :param file_new: 第二個文件
    :return:
    """
    name = file_old.split('\\')[-1]
    fp1 = open(file_old, 'rb')
    contents = fp1.read()
    fp1.close()
    old_md5 = hashlib.md5(contents).hexdigest()
    fp2 = open(file_new, 'rb')
    contents = fp2.read()
    fp2.close()
    new_md5 = hashlib.md5(contents).hexdigest()
    if old_md5 == new_md5:
        # print(f'文件{name}沒有變化')
        return False
    else:
        return True


def remain_file(old, report_html):
    """
    檢測生成測試報告的數量和對比文件的數量一致說明已經全部檢測完畢
    :param old: 全部待對比的文件
    :param report_html: 已經生成的測試報告
    :return:
    """
    tempcount = []  # 定義一個空的全部表報告列表
    for i in range(len(old)):
        tempcount.append(old[i].replace('.txt', '.txt.html'))
    while True:
        time.sleep(60)
        path = os.path.abspath(os.getcwd())
        out_file = f'{path}\\result'
        report_list = os.listdir(out_file)  # 這個是已經生成的報告
        temp_list = report_list + report_html  # 這個是不需要對比和生成的報告的拼接列表
        for x in temp_list:
            if x in tempcount:
                tempcount.remove(x)
        if len(tempcount) == 0:
            break
        else:
            print(f"還有---【{len(tempcount)}】---個表格沒有對比出結果,表格如下")
            filecount = []
            for y in tempcount:
                filecount.append(y.split('.')[0])
            print(filecount)


if __name__ == '__main__':
    path = os.path.abspath(os.getcwd())
    file_path = [f'{path}\\old', f'{path}\\new']
    old = file_check(file_path[0], 0)
    print(f"一共{len(old)}個文件需要對比,文件對比開始...")
    report_html = []
    p = Pool(9)
    for i in range(len(old)):
        file_old = file_path[0] + f'\\{old[i]}'
        file_new = file_path[1] + f'\\{old[i]}'
        results = md5_check(file_old, file_new)
        if results:
            p.apply_async(compare_file, args=(file_old, file_new, ))
        else:
            report_html.append(file_old.split('\\')[-1].replace('.txt', '.txt.html'))
    remain_file(old, report_html)
    p.close()
    p.join()
    print('文件對比結束!')
    print(time.asctime(time.localtime()))

 

 然后用批處理腳本來執行,代碼如下,-i是為了執行之后python窗口不退出,

start python -i comparefile.py

如果你電腦上安裝了多版本的python,使用下面代碼,此腳本是基於python3.7開發的用 -3來識別版本

start py -3 -i comparefile.py

文本的目錄結構,當然你也可以更改的,要在主代碼中改掉即可

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM