#!/usr/bin/python import os import re def getFile(path): fList = os.listdir(path) #将指定目录内的文件以列表格式输出 os.chdir(path) docuPath = os.getcwd() #获取根路径 fileList = [] for f in fList: #对目录内的文件进行遍历 if os.path.isdir(f): #判断文件类型是否为目录 getFile(f) #如果目录,递归运行此函数,继续进行遍历。 else: fl = os.path.join(docuPath,f) #若不是目录,则结合文件名和根路径得到文件的绝对路径 fileList.append(fl) #print(fileList) return fileList def changeFile(): for j in getFile("/opt"): #这里调用上个函数输出的fileList列表 a = open(j,"r") #打开每一个文件 b = a.read() if re.findall("hello",b): #判断文件内容里是否含有“hello” c = open(j,"w") c.write("HELLO!\n") #若含有,将“hello”改成“HELLO”。 a.close() changeFile()