递归删除的思路

def delete_dir(folder): for path in os.listdir(folder): # 如果path是文件夹 delete_dir(path)
        # 如果是文件os.remove(path)
        pass
    # for走完了代表folder内部删空了,可以删folder

递归遍历打印目标路径中所有的txt文件

def print_txt(folder): if not os.path.exists(folder) or os.path.isfile(folder): return
    for path in os.listdir(folder): file_path = os.path.join(folder, path) if os.path.isfile(file_path) and file_path.endswith('.txt'): print(path) elif os.path.isdir(file_path): print_txt(file_path) # 递归
 target_path = os.path.join(BASE_DIR, 'part6', 'target') print_txt(target_path)

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。