文件夹文件批量重命名Python代码需求:基于Excel表映射规则
Hey there! As a mechanical engineer dealing with wear analysis data, I get how tedious manual file renaming can be. Here's a straightforward Python script that’ll handle this batch rename task for you using your Excel mapping table.
Step 1: Install Required Libraries
First, you’ll need pandas to read the Excel file, plus openpyxl to support .xlsx files. If you don’t have these installed yet, run this in your terminal:
pip install pandas openpyxl
(If your Excel file is in .xls format, use xlrd instead of openpyxl.)
Step 2: The Python Script
Copy this code into a .py file, then adjust the paths to match your setup:
import pandas as pd import os # ---------------------- CONFIGURE THESE PATHS ---------------------- excel_file_path = "path/to/your/WearMappingTable.xlsx" # Replace with your Excel file path target_folder = "path/to/your/files/folder" # Replace with your files' folder path # ------------------------------------------------------------------- # Read the Excel data into a DataFrame # Use sheet_name="YourSheetName" if your data isn't on the default sheet df = pd.read_excel(excel_file_path) # Iterate through each row in the Excel table for index, row in df.iterrows(): original_name = row["Actual File Name in folder"] new_name = row["To be Renamed to"] # Create full file paths original_path = os.path.join(target_folder, original_name) new_path = os.path.join(target_folder, new_name) # Only rename if the original file exists if os.path.exists(original_path): os.rename(original_path, new_path) print(f"Renamed: {original_name} → {new_name}") else: print(f"Warning: File not found - {original_name} (skipping)") print("\nBatch rename process finished!")
Critical Safety & Usage Tips
- Backup First: Always make a copy of your files before running the script—accidents happen, and it’s easy to recover from a backup.
- Path Accuracy: Double-check the
excel_file_pathandtarget_foldervalues. Typos here will cause the script to fail. - Avoid Duplicates: Ensure none of the "To be Renamed to" values are identical—duplicates will overwrite files without warning.
- Column Name Match: Make sure your Excel column names exactly match the ones in the script (
"Actual File Name in folder"and"To be Renamed to"). If they differ, update the row accessors in the code.
Alternative: Dynamically Generate New Names
If you ever want to skip pre-filling the "To be Renamed to" column and generate the new name directly from the Wear-Num value, replace the new_name line with:
new_name = f"{row['Wear-Num']}-{row['Actual File Name in folder']}"
This will automatically prepend the Wear-Num to the original filename, just like your example shows.
内容的提问来源于stack exchange,提问作者Sushma

