python 修改某一目录下文件名

时间:2021-09-09 02:28:00

# -*- coding: gbk -*-
import sys,string,os,shutil
def RenameFiles(srcdir,prefix):
 try:
  srcfiles = os.listdir(srcdir)
  index = 1
  for srcfile in srcfiles:
   print("文件:" + srcfile)
   srcfilename = os.path.splitext(srcfile)[0][1:]
   sufix = os.path.splitext(srcfile)[1]
   #print(sufix)
   destfile = srcdir + "/" + prefix + "_%04d"%(index) + sufix
   srcfile = srcdir + "/" + srcfile
   os.rename(srcfile,destfile)
   index +=1
   print("修改后:" + destfile)
 except:
  print("请核对您的输入!")
  return 0

over = True
while over:
 print("请输入文件夹路径:")
 srcdir = input()      #srcdir = "d:/music"
 print("请输入修改文件名格式(如:输入aa 文件名改为:aa_0001.mp3):")
 prefix = input()      #prefix = "IMG_2014"
 result = RenameFiles(srcdir,prefix)
 if result != 0:
  print("修改完毕,请查看")
 print("是否继续?y/n")
 yn = input()
 if yn == "y":
  over = True
 else:
  over = False
else:
 print("完成所有修改")