【Python】按照文件夹名称批量命名文件夹内的文件

#!/usr/bin/python

# 将dir目录子文件夹中的文件按照子文件夹名称重命名
# dir 目录有子文件夹 A、B,将子文件夹 A 中的文件命名为 A_1 A_2 A_3,子文件夹B中文件命名为 B_1 B_2

import os

dir = r'D:\caffe-gpu-python3-unsamplelayer\caffe-windows\python\test-jpg'
 
def ReName(dir):
  for dirpath, dirnames, filenames in os.walk(dir):
     for dirname in dirnames:
       everydir = os.path.join(dirpath,dirname)
       i = 0
       print("start rename : %s ." % dirname)   
       for filename in os.listdir(everydir):
          filetype = filename.split(".")[1]
          i = i + 1
          newname = str(dirname) + "_" + str(i) + "." + filetype
          os.rename( os.path.join(everydir,filename),os.path.join(everydir,newname))  
       print(" %d files have been renamed." % i) 

ReName(dir)

你可能感兴趣的:(python,python)