python遍历文件夹实现照片重命名

  1. 使用os.walk
  2. 使用enumerate
  3. 使用split,可以进一步延伸re.split的模式

:END:

# *
# *  @author Zhaoliang Ye 叶昭良(zl_ye@qny.chng.com.cn)
# *  @version V0.1
# *  @Title: python.py
# *  @Description: os.walk遍历文件夹 执行判断和 按一定规则重命名
# *  @Time: 2022/2/12 0:26
# *

import os
processDir="d://test1"
imagePattern=["jpg","jpeg","png","tif","bmp"]
for root,dirs,files in os.walk(processDir):
    for i,file in enumerate(files):
        absfilename=os.path.join(root,file)
        print(f'root={root}\t dirs={dirs} \tfile={file} \t absfilename={absfilename}')
        img_type=absfilename.split(".")[1]
        print(f' img_type = {img_type}')
        if  img_type.lower() in imagePattern:
            newname=os.path.join(root,f'{i}.{img_type}')
            os.rename(absfilename,newname)
            print(f'\033[1;32m {absfilename} has been change into {newname}')
Related
叶昭良
叶昭良
Engineer of offshore wind turbine technique research

My research interests include distributed energy, wind turbine power generation technique , Computational fluid dynamic and programmable matter.