需求背景:
批量修改指定文件夹下相似的文件名,提取文件名有效信息,精简文件名。
如:
修改前:
修改后:
修改前:
修改后:
说明:
(1)在修改其他格式的文件名时需要适配 RE_FILE_NAME_FORMAT
(2)将格式相似的文件夹名添加到pathString中
新建batchRename.py
# -*- coding:utf-8 -*-
import os
import re
RE_FILE_NAME_FORMAT = "(\d{2,3})-尚硅谷-Java语言高级-(.*)\.avi"
pathString = """
D:\Edisk\python\BatchRename
D:\BaiduNetdiskDownload\day18_IDEA的使用与多线程
"""
class BatchRename():
def __init__(self, str):
self.path = []
pathList = str.split()
for path in pathList:
path = os.path.abspath(path)
if(os.path.exists(path)):
self.path.append(path)
print({"self.path":self.path})
def getFileNames(self, path):
return os.listdir(path)
def renameOnefile(self, src_name, dst_name):
os.rename(src_name, dst_name)
def batchRename(self, path):
fileNames = self.getFileNames(path)
print("修改前:{}-{}".format(path,fileNames))
rule = re.compile(RE_FILE_NAME_FORMAT)
for fileName in fileNames:
if fileName.endswith('.avi'):
subNames = rule.findall(fileName)
if(len(subNames) > 0):
sn, name = subNames[0]
newFileName = "{}-{}.avi".format(sn,name)
srcName = os.path.join(os.path.abspath(path), fileName)
dstName = os.path.join(os.path.abspath(path), newFileName)
self.renameOnefile(srcName, dstName)
print("修改后:{}-{}".format(path, self.getFileNames(path)))
def runBatchProc(self):
for path in self.path:
self.batchRename(path)
if __name__ == '__main__':
print("""
**************************************************
匹配方式:
修改RE_FILE_NAME_FORMAT正则表达式
使用方法:
1,在pathString添加需要修改文件名的路径在
2,打开cmd终端
3,执行:python batchRename.py
**************************************************
""")
batch = BatchRename(pathString)
batch.runBatchProc()