#!/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()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。