首页 > 编程语言 > 详细

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

时间:2019-07-23 20:02:01      阅读:82      评论:0      收藏:0      [点我收藏+]
#!/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()

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!