Discuss / Python / 第二题作业:遍历目录

第二题作业:遍历目录

Topic source

用os.walk遍历目录

def findall_file(filename,Dir = os.getcwd()):    filelist = []    for root,dirs,files in os.walk(Dir):        for file in files:            if file == filename:                filelist.append(os.path.join(root,file))    return filelist

审题错误,上面那个是错的,没有输出相对路径,而且只能查找文件全名。改进:

def findall_file(filename,Dir = os.getcwd()):    filelist = []    for roots,dirs,files in os.walk(Dir):            for file in files:                if  filename in file:                    relatpath = os.path.join(roots,file).split(Dir)[1].replace('\\','//')                    filelist.append(relatpath)    return filelist

  • 1

Reply