You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写基于扩展名的文件重命名脚本:需求实现问询

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 txt or .txt both work).
  • Date Prefix: The default prefix uses your system's current date in YYYY-DD-MM format—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 separator variable (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:

  1. Save the script as rename_files.py
  2. Open a terminal/command prompt, navigate to the folder with your target files
  3. Run the script with python rename_files.py
  4. Follow the prompts to set your extension, prefix, and confirm the changes

内容的提问来源于stack exchange,提问作者user3296793

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:03:58