python3 文件夹下代码比较工具

# diff.py 仅比较两个路径下的同名文本文件,遇到不同名或内容不同的则停止
import os
import sys


def compare_2_file(path1, path2):
    try:
        fd1 = open(path1, "r", encoding="utf-8")
        fd2 = open(path2, "r", encoding="utf-8")
    except Exception as e:
        print(10, e)
        return False
    try:
        i = 0
        for line1, line2 in zip(fd1, fd2):
            i += 1
            if not line1 == line2:
                print(i, line1)
                print(i, line2)
                return False
        return True
    except Exception as e:
        print(20, e)
        return False
    finally:
        fd1.close()
        fd2.close()


def show_diff(dir1, dir2):
    dir_list_1 = os.listdir(dir1)
    dir_list_2 = os.listdir(dir2)
    for path1, path2 in zip(dir_list_1, dir_list_2):
        path1 = os.path.join(os.path.dirname(dir1), os.path.basename(dir1), path1)
        path2 = os.path.join(os.path.dirname(dir2), os.path.basename(dir2), path2)
        if os.path.isdir(path1) and os.path.isdir(path2):
            if not show_diff(path1, path2):
                return False
        elif not os.path.isdir(path1) and not os.path.isdir(path2):
            if not compare_2_file(path1, path2):
                print(path1)
                print(path2)
                return False
        else:
            print(path1)
            print(path2)
            return False

    return True


if __name__ == '__main__':
    _, dir1, dir2 = sys.argv
    print(show_diff(dir1, dir2))

python diff.py abs_path1 abs_path2

posted @ 2021-09-17 17:09  玉北  阅读(142)  评论(0编辑  收藏  举报