Discuss / Python / 第二题:用了递归

第二题:用了递归

Topic source

久疤_796

#1 Created at ... [Delete] [Delete and Lock User]
'''
遍历当前目录及其子目录下文件名包含指定字符串的文件的绝对路径
'''
def fun(name,path='.',res=set([])):
    path = os.path.abspath(path)
    L = os.listdir(path)
    for x in L:
        tpath = os.path.join(path,x)
        if os.path.isfile(tpath):
            if name in os.path.split(os.path.splitext(tpath)[0])[1]:
                res.add(tpath)
        elif os.path.isdir(tpath):
            fun(name,tpath,res)
    return res

L = fun('t')
print(L,len(L))

久疤_796

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

据说os.walk更好???


  • 1

Reply