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()
相關文章
相關標籤/搜索