範例效果:
1.取代某資料夾下的資料夾及子資料夾的名稱 由OldStrDir 變成NewStrDir;
#2.取代某資料夾下的資料夾及子資料夾下所有的檔案的名稱 由OldStrFile 變成NewStrFile;
3.取代某資料夾下的資料夾及子資料夾下所有的檔案的內容 由OldStrContent 變成NewStrContent;
對應程式碼:
# -*- coding: UTF-8 -*- import os import re #replace dir name def replaceDirName(rootDir,oldStr,newStr): for parent,dirNames,fileNames in os.walk(rootDir,topdown=False): for dirName in dirNames: if oldStr in dirName: dirNameOld = os.path.join(parent,dirName) dirNameNew = os.path.join(parent,dirName.replace(oldStr,newStr)) print(dirNameOld + ' --> ' + dirNameNew) os.rename(dirNameOld,dirNameNew) #replace file name def replaceFileName(rootDir,oldStr,newStr): for parent,dirNames,fileNames in os.walk(rootDir): for fileName in fileNames: if oldStr in fileName: fileNameOld = os.path.join(parent,fileName) fileNameNew = os.path.join(parent,fileName.replace(oldStr,newStr)) print(fileNameOld + ' --> ' + fileNameNew) os.rename(fileNameOld,fileNameNew) #replace file content name def replaceFileContent(rootDir,oldStr,newStr): for parent,dirNames,fileNames in os.walk(rootDir): for fileName in fileNames: fileObj = os.path.join(parent,fileName) f = open(fileObj,'r+') all_the_lines=f.readlines() f.seek(0) f.truncate() for line in all_the_lines: f.write(line.replace(oldStr,newStr)) f.close() def main(): rootDir = "D:/D" oldStr = "CustomerType" newStr = "CustomerAttr" replaceDirName(rootDir,oldStr,newStr) replaceFileName(rootDir,oldStr,newStr) replaceFileContent(rootDir,oldStr,newStr) if __name__=='__main__': main()
以上是使用python替換資料夾下的檔案名稱及檔案內容方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!