时间:2021-07-01 10:21:17 帮助过:130人阅读
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替换文件夹下的文件名称及文件内容方法介绍的详细内容,更多请关注Gxl网其它相关文章!