# 如果有帮助,请点个赞,感谢!
import os
import re
print('【注释:暂支持win系统!】')
def FILEpath():
while True:
inputpath = input('>>输入批量重命名文件夹的绝对路径(例如:D:\新建文件夹):')
filepath = inputpath.strip() # 去除前后空格
if os.path.exists(filepath): # 判断输入文件夹路径是否存在
filenumber = len(os.listdir(filepath)) # 计算文件数量
print('【该文件夹下存在文件数' + str(filenumber) + '。】')
return filepath # 存在即返回路径
else:
print('【提示:请正确输入绝对路径。】')
continue
def NAMED(filepath):
while True:
inputname = input('>>输入新文件名:')
if inputname and re.search(r"\W", inputname) == None: # 判断是否输入文件名以及特殊字符存在
break
else:
print('【提示:请正确输入新文件名且不能包含特殊字符。】')
continue
for file in os.listdir(filepath): # 依次处理文件夹下文件
filename = os.path.splitext(file) # 处理文件名以及后缀名
lnumber = ''
while True:
newname = file.replace(file, inputname + str(lnumber) + filename[1]) # 替换新命名
newfile = os.path.join(filepath, newname) # 拼接文件路径
if newfile == os.path.join(filepath, file): # 判断新命名是否重名原文件
break
else:
if os.path.exists(newfile): # 检查是否存在其它重名文件
if lnumber == '':
lnumber = 0
lnumber += 1
continue
else:
lnumber += 1
continue
else:
os.rename(os.path.join(filepath, file), newfile) # 新命名文件
print('原文件名[' + file + ']更改为:' + newname)
break
if __name__ == '__main__':
NAMED(FILEpath())
原文链接:https://blog.csdn.net/AnotherQuiet/article/details/111660677