Python递归遍历文件夹批量替换某字符串改名

情景:
在某拼平台买了一门课程,而后发现所有的视频和源代码**都在文件名后面拼接了一段字符串:
“【加微信#######赠送精品IT课程】”
这种问题通过Python写一个小脚本即可
源代码如下:

import os

# rootDir = os.getcwd()
rootDir = os.path.dirname(__file__)

def renameFile(filename):
    # do something
    print('renameing file:', filename)
    oriName = filename
    tarName = filename.replace('{这里写要被替换掉的字符串}', '')

    print('oriname', oriName, '-tar name', tarName)
    os.rename(oriName, tarName)
    
def getAllFiles(path):
    thisSubDir = os.listdir(path)
    for fileOrDir in thisSubDir:
        thisPath = os.path.join(path, fileOrDir)
        if os.path.isdir(thisPath): #如果是文件夹
            getAllFiles(thisPath)   #继续去递归
        else:
            renameFile(thisPath)
            
    
if __name__ == '__main__':
    print('Start processing......')
    print('Start get all files in dir:', rootDir)
    getAllFiles(rootDir)

博客搬家验证:
var code = “c0e95672-984c-4f5e-8ad7-1a32b20a5881”

posted @ 2023-01-19 11:29  PushyTao  阅读(41)  评论(0编辑  收藏  举报  来源