python脚本重命名文件
代码如下:
import os
import pandas as pd
def rename_files_based_on_excel(excel_path, folder_path, id_column='id', old_name_column='ori_name', new_name_column=None):
# 读取Excel文件
df = pd.read_excel(excel_path)
# 获取文件夹中的所有文件
files = os.listdir(folder_path)
# 如果没有指定新的名称列,则默认使用ID列作为新文件名
if not new_name_column:
new_name_column = id_column
# 遍历DataFrame中的每一行
for index, row in df.iterrows():
old_file_name = None
# 尝试找到文件名中包含ID的文件
for file in files:
if str(row[old_name_column]) in file:
old_file_name = file
break
# 如果找到了匹配的文件,则重命名
if old_file_name is not None:
# 构建新的文件名,保持原有的扩展名
file_extension = os.path.splitext(old_file_name)[1]
new_file_name = f"{str(row[new_name_column]).strip()}{file_extension}"
# 确保新旧文件名不同
if old_file_name != new_file_name:
old_file_path = os.path.join(folder_path, old_file_name)
new_file_path = os.path.join(folder_path, new_file_name)
try:
os.rename(old_file_path, new_file_path)
print(f'Renamed: {old_file_name} -> {new_file_name}')
except Exception as e:
print(f'Could not rename {old_file_name}: {e}')
# 使用函数,提供Excel路径、文件夹路径、ID列名以及可选的新名称列名
excel_path = r'C:\Users\xxx\Downloads\text.xls'
folder_path = r'C:\Users\xxx\Downloads\origin'
rename_files_based_on_excel(excel_path, folder_path, 'id', 'ori_name', 'new_name')
text.xls中设置 id ori_name(原名称) new_name(新名称) 列