环境:Window10 + Python3.9 + PyCharm(2023.1.3)
-------------------------------------****************** ** *********************-----------------------------------------
这是在Python中批量将指定文件夹下相似的文件名,提取文件名有效信息,精简文件名,去除烦人信息。
-------------------------------------****************** ** *********************-----------------------------------------
开始时是这样
然后让他变成了这样
Python中批量修改文件名,去除某些内容
-------------------------------------****************** ** *********************-----------------------------------------
代码实现:
# --** coding="UTF-8" **--
# project:Small_Case
# author:SueMagic time:2019-05-11
# latest time:2024-04-02
import os, time
import re
import sys
# 02-imageonline.co-61986-1
# origin1-imageonline.co-921510-4
RE_FILE_NAME_FORMAT = "[a-zA-Z0-9_]+-imageonline.co-(\d{5,7})-(.*)\.png"
pathString = """
D:\picture\imageonline.co-01
D:\picture\imageonline.co-02
D:\picture\imageonline.co-03
D:\picture\imageonline.co-04
D:\picture\imageonline.co-05
D:\picture\imageonline.co-06
D:\picture\imageonline.co-07
D:\picture\imageonline.co-08
"""
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 change_suffix(self, path):
"""
修改文件名,叠加数字
"""
def change_file_name(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)
print("现在rule是" + str(rule))
for fileName in fileNames:
if fileName.endswith('.png'):
subNames = rule.findall(fileName)
if (len(subNames) > 0):
sn, name = subNames[0]
newFileName = "{}-{}.png".format(sn, name)
print("这里是" + str(newFileName))
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__':
batch_name = BatchRename(pathString)
batch_name.runBatchProc()
# change_suffix()
# change_file_name()
-------------------------------------****************** ** *********************-----------------------------------------