遍历根目录下包含特定字符串的文件

import os
import re


name = raw_input("please input the name: ")
for dirpath, dirnames, filenames in os.walk(os.path.join('/home/xiao', name), True, None):
    for filename in filenames:
        if re.search('test', filename):
        # if 'test' in filename:
            print os.path.join(dirpath, filename)

函数声明:os.walk(top,topdown=True,onerror=None)

(1)参数top表示需要遍历的顶级目录的路径。

(2)参数topdown的默认值是“True”表示首先返回顶级目录下的文件,然后再遍历子目录中的文件。当topdown的值为"False"时,表示先遍历子目录中的文件,然后再返回顶级目录下的文件。

(3)参数onerror默认值为"None",表示忽略文件遍历时的错误。如果不为空,则提供一个自定义函数提示错误信息后继续遍历或抛出异常中止遍历。

os.walk这个方法返回的是一个三元tupple(dirpath, dirnames, filenames),

其中第一个为起始路径,

第二个为起始路径下的文件夹,

第三个是起始路径下的文件. dirpath是一个string,代表目录的路径, dirnames是一个list,包含了dirpath下所有子目录的名字, filenames是一个list,包含了非目录文件的名字.这些名字不包含路径信息,如果需要得到全路径,需要使用 os.path.join(dirpath, name).

import os
import re


def searchAndPrint(path):
    findFiles = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and re.search('test', f)]
    for f in findFiles:
        print os.path.join(path, f)
    subDirs = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
    for d in subDirs:
        searchAndPrint(os.path.join(path, d))

name = raw_input("please input the name: ")
searchAndPrint(os.path.join('/home/xiao', name))

  

原文地址:https://www.cnblogs.com/tuifeideyouran/p/4186766.html