假如有如下目录结构:
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,getopt
dirHome='app_'
'''解析参数文件'''
def parseCofig(configFile):
try:
global contentPairs
global dirPairs
if (os.path.exists(configFile) and os.path.isfile(configFile)) :
cf = configparser.RawConfigParser()
cf.optionxform = lambda option: option
cf.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 str
return None
def 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 newFilePath
def main():
argArr=sys.argv
if(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=one
second=two