Rename multiple files inside multiple folders

前端 未结 3 583
一整个雨季
一整个雨季 2021-01-24 01:50

So I have a lot of folders with a certain name. In each folder I have +200 items. The items inside the folders has names like:

CT.34562346.246.dcm
RD.34562346.dc         


        
3条回答
  •  醉酒成梦
    2021-01-24 02:13

    This will rename files in subdirectories too:

    import os
    rootdir = "foo" + os.sep + "bar"
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            filepath = subdir + os.sep + file
            foldername = subdir.split(os.sep)[-1]
    
            number = ""
            foundnumber = False
    
            for c in filepath:
                if c.isdigit():
                    foundnumber = True
                    number = number + c
                elif foundnumber:
                    break
            if foundnumber:
                newfilepath = filepath.replace(number,foldername)
                os.rename(filepath, newfilepath)
    

提交回复
热议问题