python_exercise_能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径

import os


def find_file_by_str(path, str):

    list_file_name = []
    list_file_path = []

    for file in os.listdir(path):               # 遍历当前路径下的文件及目录
        this_path = os.path.join(path, file)
        if os.path.isfile(this_path):
            if str in this_path:
                list_file_name.append(this_path)
                list_file_path.append(this_path.split(os.path.abspath('..'))[-1])
                print('包含指定字符串 {} 的文件之一是 {}, 相对路径是 {} '.format(str, list_file_name[0], list_file_path[0]))
        else:                                   # 如果是目录的话,再次执行本方法
            find_file_by_str(this_path, str)

find_file_by_str(os.path.abspath("."), 'qu')

猜你喜欢

转载自www.cnblogs.com/jianjiacangcang/p/10587119.html