1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > [python]一个遍历多层文件夹 然后替换文件内容和目录名称的案例

[python]一个遍历多层文件夹 然后替换文件内容和目录名称的案例

时间:2021-01-11 14:10:43

相关推荐

[python]一个遍历多层文件夹 然后替换文件内容和目录名称的案例

假如有如下目录结构:

root

first

a.txt

b.txt

second

c.txt

d.txt

third

first

a.txt

second

需要把所有文件中的变量 ${txt_date} 替换为 ${start_date},把所有名称为first的目录改为one、second的目录改为two

代码:

import os,time,configparser,sys,getoptdirHome='app_''''解析参数文件'''def parseCofig(configFile):try:global contentPairsglobal dirPairsif (os.path.exists(configFile) and os.path.isfile(configFile)) :cf = configparser.RawConfigParser()cf.optionxform = lambda option: optioncf.read(configFile)contentPairs = cf.items('file')dirPairs = cf.items('dir')return 0;else:writeLog("ERROR", "config file [" + configFile + "] not exists!")exit(1)except Exception as e:writeLog("ERROR", str(e))exit(1)#打印日志def writeLog(logtype, msg):print("[{:5}][{}] {}".format(logtype, time.strftime("%Y-%m-%d %H:%M:%S"), msg))return'''遍历文件夹'''def walkFile(file):try:if os.path.isdir(file):for root, dirs, files in os.walk(file):writeLog("INFO", "scan directory [" + root + "]")if(len(files)==0 and len(dirs)==0):writeLog("WARN", "directory [" + root + "] is null!")handleFile(root)else:for f in files:handleFile(os.path.join(root, f))else:handleFile(file)except Exception as e:writeLog("ERROR", str(e))exit(1)def handleFile(file):target = replacePath(file)dir=''if(os.path.isfile(os.path.abspath(file))):dir = os.path.dirname(os.path.abspath(target))else:dir = os.path.abspath(target)#创建目录if(os.path.exists(dir) and os.path.isdir(dir)):{#writeLog("WARN", "directory [" + dir + "] already exists!")}else:{ os.mkdir(dir) }#替换文件变量if (os.path.isfile(file)):str = replaceContent(file)writeLog("INFO", "write [" + os.path.abspath(file) + "] to ["+os.path.abspath(target)+"]")with open(target, 'w', encoding='utf-8') as f:f.write(str)def replaceContent(file):writeLog("INFO", "replace file content,fileName[" + file + "]")with open(file, 'r', encoding='utf-8') as f:str = f.read()for p in contentPairs:if len(p) == 2:str = str.replace(p[0], p[1])return strreturn Nonedef replacePath(filePath):newFilePath=''for p in dirPairs:if len(p) == 2:newFilePath = dirHome+filePath.replace(p[0], p[1])if(filePath!=newFilePath):writeLog("INFO", "replace file directory [" + filePath + "] to "+"["+newFilePath+"]")return newFilePathdef main():argArr=sys.argvif(len(argArr)<=1):parseCofig("parm.txt")walkFile("root")elif(len(argArr)==2):parseCofig("parm.txt")walkFile(argArr[1])elif(len(argArr)==3):parseCofig(argArr[1])walkFile(argArr[2])else:writeLog("ERROR", "arg error!")main();

把以上代码文件放入和root目录相同的目录中

在和root目录相同的目录中编辑一个参数文件parm.txt,内容为:

[file]${txt_date}=${start_date}[dir]first=onesecond=two

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。