import os
import shutil
import pandas as pd
def clean_filename(filename):
"""
清理文件名中的特定符号,将它们替换为破折号(-)。
"""
symbols = ['<', '>', ':', '"', '/', '\\', '|', '?', '*']
for symbol in symbols:
filename = filename.replace(symbol, '-')
return filename
def rename_and_move_images(read_col, name_col, folder_path, excel_path):
# 删除旧的文件夹(如果存在)
for folder_name in ['重命名完', '未重命名']:
folder_to_delete = os.path.join(folder_path, folder_name)
if os.path.exists(folder_to_delete):
shutil.rmtree(folder_to_delete)
# 在目标地址下创建新的文件夹
os.makedirs(os.path.join(folder_path, '重命名完'))
os.makedirs(os.path.join(folder_path, '未重命名'))
# 读取Excel文件
df = pd.read_excel(excel_path)
# 读取所有子文件夹,排除掉“重命名完”和“未重命名”
for subdir, dirs, files in os.walk(folder_path):
if subdir in [os.path.join(folder_path, '重命名完'), os.path.join(folder_path, '未重命名')]:
continue # 跳过特殊文件夹
dirs[:] = [d for d in dirs if d not in ['重命名完', '未重命名']] # 修改dirs列表,排除特定文件夹
for dir_name in dirs:
full_dir_path = os.path.join(subdir, dir_name)
matching_rows = df[df.iloc[:, read_col - 1] == dir_name]
if not matching_rows.empty:
new_name_base = clean_filename(matching_rows.iloc[0, name_col - 1])[:255]
image_counter = 1
for file in os.listdir(full_dir_path):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
new_name = f"{new_name_base}({image_counter}){os.path.splitext(file)[1]}"
new_name = clean_filename(new_name)
# 缩短文件名如果它超过了Windows的限制
new_path = os.path.join(full_dir_path, new_name)
if len(new_path) > 260:
# 缩短文件名保持在限制内
new_name = f"{new_name_base[:10]}...({image_counter}){os.path.splitext(file)[1]}"
os.rename(os.path.join(full_dir_path, file), os.path.join(full_dir_path, new_name))
image_counter += 1
# 移动整个文件夹
shutil.move(full_dir_path, os.path.join(folder_path, '重命名完'))
else:
# 如果不存在,移动整个文件夹到“未重命名”
shutil.move(full_dir_path, os.path.join(folder_path, '未重命名'))
# 用户输入
read_col = int(input("请输入Excel表格的读取列(数字): "))
name_col = int(input("请输入Excel表格的命名列(数字): "))
folder_path = input("请输入文件夹结构层级地址: ")
excel_path = input("请输入Excel表格的路径: ")
rename_and_move_images(read_col, name_col, folder_path, excel_path)