当前位置:首页 > Python教程 > python技巧

python3.7脚本---遍历指定目录内所有文件

#!/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()

原文:https://blog.51cto.com/11954248/2422945


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐