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

如题;


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

import os

#中文文件夹会出错,未能解决

def search(path, s):
    listfile = [x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]
    for f in listfile:
        # f 字符串包含 s 字符串
        if s in f:
            print(os.path.join(path, f))
    listdir = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
    for d in listdir:
        search(os.path.join(path, d), s)
search('.', 'a') #从当前目录开始


你可能感兴趣的:(Python)