Discuss / Python / 如果是文件夹,子路径下进行递归调用

如果是文件夹,子路径下进行递归调用

Topic source

飞侠100

#1 Created at ... [Delete] [Delete and Lock User]
import os

def search(str, path='.'):
    for x in os.listdir(path):
        if os.path.isdir(x):
            # 如果是文件夹,子路径下进行递归调用
            new_path = os.path.join(path,x)
            search(str, new_path)
        else:
            if str in x:
                print(os.path.join(path,x))

zjdddlll

#2 Created at ... [Delete] [Delete and Lock User]

学到了,抱拳。

十夢玖祢i

#3 Created at ... [Delete] [Delete and Lock User]

指出一个错误,os.path.isdir(path)中的path必须为绝对路径,否则判断会错误,结果就是会导致子目录中包含关键字的目录也错误打印出来,而题目要求只能打印文件的路径

import os

def search(path,key):
    for x in os.listdir(path):
        #如果是文件,打印
        if os.path.isfile(os.path.join(path,x)):
            if key in x:
                print(os.path.join(path,x))
        #如果是目录,递归
        if os.path.isdir(os.path.join(path,x)):
            new_path = os.path.join(path,x)
            search(new_path,key)

  • 1

Reply