通过三个案例,介绍批量修改文件名字的方法。
一、批量在文件前/后任意添加文件名字
二、批量去掉文件字符
三、批量替换某一类型文件名字
一、批量在文件前/后任意添加文件名字(批量在文件前面添加‘方法11’字符)
#在文件前面/后面批量修改文件名字
def filename_modify(target_dir,addstr='end'):
#判断路径是否存在
if os.path.exists(target_dir) == False:
raise Exception('path is not exist')
#遍历文件夹中的文件名
for file in os.listdir(target_dir):
#分割文件名和拓展名
filename = os.path.splitext(file)[0]
fileExpand = os.path.splitext(file)[1]
#不修改文件夹的名字 (方法二:判断文件名是否为空)
if fileExpand == '':
continue
#将所有文件的后面添加-kkb
newname = filename + addstr + fileExpand
#修改名字
oldpath = os.path.join(target_dir,file) #老路径
newpath = os.path.join(target_dir,newname) #新路径
os.rename(oldpath,newpath)
pass
filename_modify('D:\Anaconda',addstr='方法11')
二、批量去掉文件字符(批量去掉文件中‘’方法‘’字符)
#批量修改文件名字,将所有文件中的方法11去掉
import re
def filename_modify(target_dir,addstr='',position = 'end',oldstr='',newstr=''):
#判断路径是否存在
if os.path.exists(target_dir) == False:
raise Exception('path is not exist')
#遍历文件夹中的文件名
for file in os.listdir(target_dir):
#分割文件名和拓展名
filename = os.path.splitext(file)[0]
fileExpand = os.path.splitext(file)[1]
#不修改文件夹的名字 (方法二:判断文件名是否为空)
if fileExpand == '':
continue
#判断添加的位置
if position == 'end':
#将所有文件的后面添加-kkb
newname = filename + addstr + fileExpand
elif position == 'head':
#将所有文件的后面添加-kkb
newname = addstr + filename + 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_dir,file) #老路径
newpath = os.path.join(target_dir,newname) #新路径
os.rename(oldpath,newpath)
# print( newname)
pass
filename_modify('D:\Anaconda',position = 'replace',oldstr = '方法',newstr = '')
三、批量替换某一类型文件名字 (批量在xls文件前面添加abc字符)
#批量修改某类文件名字
import re
def filename_modify(target_dir,addstr='',position = 'end',oldstr='',newstr='',filetype=None):
# target_dir 路径 ;addstr 添加的字符 ; position 添加的位置 end结尾 head 开头;oldstr 替换的旧字符 ;
#newstr 替换的新字符 ; filetype 指定类型
#判断路径是否存在
if os.path.exists(target_dir) == False:
raise Exception('path is not exist')
#遍历文件夹中的文件名
for file in os.listdir(target_dir):
#分割文件名和拓展名
filename = os.path.splitext(file)[0]
fileExpand = os.path.splitext(file)[1]
#不修改文件夹的名字 (方法二:判断文件名是否为空)
if fileExpand == '':
continue
#过滤文件类型,从而达到修改指定类型
if filetype != None and filetype not in fileExpand:
continue
#判断添加的位置
if position == 'end':
#将所有文件的后面添加
newname = filename + addstr + fileExpand
elif position == 'head':
#将所有文件的后面添加
newname = addstr + filename + 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_dir,file) #老路径
newpath = os.path.join(target_dir,newname) #新路径
os.rename(oldpath,newpath)
# print( newname)
pass
filename_modify('D:\Anaconda',
position = 'head',addstr = 'abc',
filetype = 'xls')