import os
import re
def filename_modify(target,expandname,position = "end",oldstr = "",newstr = ""):
#判断路径是否存在
if os.path.exists(target) == False:
raise Exception("path is not exist!")
#遍历文件夹中的名字
for file in os.listdir(target):
filename = os.path.splitext(file)[0]
fileexpand = os.path.splitext(file)[1]
# 避开文件夹
# if os.path.isdir(os.path.join(target,file)):
# continue
#避开文件夹 第二种方法
if fileexpand == "":
continue
#判断修改位置
if position == "head":
newname = expandname+filename+fileexpand
elif position == "end":
newname = filename+expandname+fileexpand
elif position == "replace":
pattern = re.findall(oldstr,filename)
for value in pattern:
filename = filename.replace(value,newstr)
newname = filename+fileexpand
oldpath = os.path.join(target,file)
newpath = os.path.join(target,newname)
os.rename(oldpath,newpath)
filename_modify("文件夹的位置","要增加的名称","修改位置","需要替换的就名称","需要替换的新名称")
网友评论