import os标签:重命名,files,name,批量,excel,MJ,parts,path,os From: https://www.cnblogs.com/zly324/p/17774950.html
import openpyxl
import re
UNWANTED_UNITS = ["undefined", "皮皮", "zly324"]
# 第一步:删名称
def rename_files(path):
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
renamed_files = []
counter = 1
for file in files:
filename, ext = os.path.splitext(file)
# 乱码类
if re.search(r'[a-f0-9]{32}', filename) or not '_' in filename:
renamed = f"({counter})"
counter += 1
# AI出图类
else:
parts = re.split(r'[_]+', filename)
parts.pop(0) # 删除第一个单元
# 删除特定的单元
parts = [part for part in parts if part not in UNWANTED_UNITS]
# 删除所有带数字的单元
parts = [part for part in parts if not any(char.isdigit() for char in part)]
# 结尾规则
# 删除UUID风格数字
while parts and re.search(r'^[a-f0-9\-]{32,}$', parts[-1]):
parts.pop(-1)
# 删除长度小于等于4的部分
while parts and len(parts[-1]) <= 4:
parts.pop(-1)
renamed = '_'.join(parts)
renamed_files.append(renamed + ext)
return renamed_files
# 第二步:增名称
def add_prefix(files, prefix):
prefixed_files = [f"{prefix}_{file}" if not file.startswith(prefix) else file for file in files]
# 删除特定的单元
prefixed_files = ['_'.join([part for part in re.split(r'[_]+', name) if part not in UNWANTED_UNITS]) for name in
prefixed_files]
return prefixed_files
# 第三步:创建Excel并自动打开
def create_and_open_excel(files, renamed_files, path):
wb = openpyxl.Workbook()
ws = wb.active
for original, renamed in zip(files, renamed_files):
ws.append([original, renamed])
excel_path = os.path.join(path, os.path.basename(path) + ".xlsx")
wb.save(excel_path)
# 打开Excel文件
os.system(f'start "" "{excel_path}"')
return excel_path
# 第五步:读取Excel并重命名文件
def rename_files_from_excel(path, excel_path):
wb = openpyxl.load_workbook(excel_path)
ws = wb.active
for row in ws.iter_rows(values_only=True):
original_name, new_name = row
target_path = os.path.join(path, new_name)
# 检查原文件是否存在
if os.path.exists(os.path.join(path, original_name)):
# 如果目标文件名已存在,则添加一个编号
counter = 1
base_name, ext = os.path.splitext(new_name)
while os.path.exists(target_path):
new_name = f"{base_name} ({counter}){ext}"
target_path = os.path.join(path, new_name)
counter += 1
os.rename(os.path.join(path, original_name), target_path)
print("重命名完成。")
# 主函数
def main():
path = input("请输入文件夹地址: ")
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
renamed_files = rename_files(path)
prefix = input("请输入需要批量命名的词: ")
prefixed_files = add_prefix(renamed_files, prefix)
excel_path = create_and_open_excel(files, prefixed_files, path)
print(f"Excel文件已保存为:{excel_path}")
print("请在Excel里微调B列数据,然后保存和关闭Excel文件。完成后按Enter键继续...")
input()
# 重命名文件
rename_files_from_excel(path, excel_path)
if __name__ == "__main__":
main()