#!/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腳本---遍歷指定目錄內所有文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.