[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,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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值