编写基于扩展名的文件重命名脚本:需求实现问询
Python Script for Extension-Based File Renaming with Custom Prefix
Here's a practical, user-friendly script that checks all your boxes. It uses Python (cross-platform, easy to tweak) and includes safety features like previewing changes before committing to avoid mistakes.
import os from datetime import date def main(): # Step 1: Get target file extension from user target_ext = input("Enter the target file extension (e.g., txt, pdf): ").strip() # Auto-add a dot if user forgets it if not target_ext.startswith('.'): target_ext = f'.{target_ext}' # Step 2: Get prefix (default to YYYY-DD-MM current date) default_prefix = date.today().strftime("%Y-%d-%m") user_prefix = input(f"Enter filename prefix (press Enter to use default: {default_prefix}): ").strip() prefix = user_prefix if user_prefix else default_prefix # Optional: Adjust separator between prefix and original filename (e.g., change to '-' or remove) separator = '_' # Step 3: Find matching files and preview renames print("\n--- Preview of Rename Changes ---") rename_queue = [] for filename in os.listdir('.'): # Skip folders, only process files with matching extension if os.path.isfile(filename) and filename.endswith(target_ext): new_filename = f"{prefix}{separator}{filename}" rename_queue.append((filename, new_filename)) print(f"Original: {filename} → New: {new_filename}") if not rename_queue: print(f"No files found with extension '{target_ext}'.") return # Step 4: Confirm and execute renames confirm = input("\nDo you want to proceed with these renames? (y/n): ").strip().lower() if confirm == 'y': for old_name, new_name in rename_queue: os.rename(old_name, new_name) print("Renaming completed successfully!") else: print("Renaming cancelled.") if __name__ == "__main__": main()
Key Details & Customization Tips:
- Extension Flexibility: The script automatically handles extensions with or without a leading dot (e.g., inputting
txtor.txtboth work). - Date Prefix: The default prefix uses your system's current date in
YYYY-DD-MMformat—just hit Enter to use it. - Preview First: You’ll see every planned rename before any files are modified, so you can catch typos or unwanted changes early.
- Separator Control: The
separatorvariable (set to_by default) lets you adjust how the prefix connects to the original filename. Change it to-, leave it empty, or use any character you prefer.
How to Run:
- Save the script as
rename_files.py - Open a terminal/command prompt, navigate to the folder with your target files
- Run the script with
python rename_files.py - Follow the prompts to set your extension, prefix, and confirm the changes
内容的提问来源于stack exchange,提问作者user3296793
相关产品推荐
相关产品推荐

