[python] 对2个文件夹进行递归diff (coding中)

博客提及单文件夹进行遍历以及两个文件夹相关内容,聚焦于文件夹遍历这一信息技术操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单文件夹进行遍历:

import os

def gen_tree(filepath, parent):
    status = [filepath, 'd', ' ']
    parent.append(status)
    files = os.listdir(filepath)
    for fi in files:
        fi_d = os.path.join(filepath, fi)
        if os.path.isdir(fi_d):
            child = []
            gen_tree(fi_d, child)
            if child:
                parent.append(child)
        else:

            status = [os.path.join(filepath, fi_d), 'f', '']
            parent.append(status)



if __name__=='__main__':
    file_tree = []
    gen_tree(r'F:/test',file_tree)
    print(file_tree)

两个文件夹

import os

orig_pathA = None
orig_pathB = None

# flag = 0, pathA and pathB are all valid
# flag = 1, pathA is valid, pathB is empty
# flag = 2, pathA is empty, pathA is valid
def gen_tree(path, flag, parent):
    status = [path, 'd', flag]
    parent.append(status)
    if flag == 0:
        # do 2 tree cmp
    else:
        files = os.listdir(path)
        for fi in files:
            fi_d = os.path.join(path, fi)
            if flag == 1:
                realpath = os.path.join(orig_pathA, fi_d)
            else:
                realpath = os.path.join(orig_pathA, fi_d)

            if os.path.isdir(realpath):
                child = []
                gen_tree(fi_d, flag, child)
                if child:
                    parent.append(child)
            else:
                status = [os.path.join(path, fi_d), 'f', flag]
                parent.append(status)


def compare_file(pathA, pathB):
    return 0


if __name__=='__main__':
    file_tree = []
    pathA = r'F:/testA'
    pathB = r'F:/testB'
    if os.path.isdir(pathA) and os.path.isdir(pathB):
        orig_pathA = pathA
        orig_pathB = pathB
        gen_tree('.', 0, file_tree)
    elif os.path.isfile(pathA) and os.path.isfile(pathB):
        issame = compare_file(pathA, pathB)
        statusA = [pathA, 'f', issame]
        statusB = [pathB, 'f', issame]
        file_tree.append(statusA)
        file_tree.append(statusB)
    else:
        print('path is not valid or type mismatch!')

    print(file_tree)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值