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

如何将文件夹内文件批量重命名为[原名_原后缀].txt及实现逆向恢复?

Got it, let's tackle your problem step by step. You need two recursive functions: one to transform non-.txt files into the originalName_originalExt.txt format, and another to reverse that process and restore the original filenames. Here's how to build them:


1. Forward Conversion: Rename Non-.txt Files to Name_Ext.txt

This function will recursively scan your target directory, skip any existing .txt files, and rename all other files to follow your desired pattern (e.g., script.py → script_py.txt).

import os

def convert_to_txt(directory):
    """
    Recursively rename all non-.txt files in the directory to "originalName_originalExt.txt"
    Original .txt files remain unchanged.
    
    Args:
        directory (str): Path to the target folder (including subfolders to process)
    """
    for foldername, _, filenames in os.walk(directory):
        for filename in filenames:
            # Skip files that are already in .txt format
            if filename.endswith('.txt'):
                continue
            
            # Split the filename into base name and original extension (with the dot)
            base_name, original_ext = os.path.splitext(filename)
            # Remove the leading dot from the extension to clean it up (e.g., ".py" → "py")
            clean_ext = original_ext.lstrip('.')
            # Build the new filename using your desired pattern
            new_filename = f"{base_name}_{clean_ext}.txt"
            
            # Construct full paths to avoid errors with subfolders
            old_file_path = os.path.join(foldername, filename)
            new_file_path = os.path.join(foldername, new_filename)
            
            # Rename the file
            os.rename(old_file_path, new_file_path)
            print(f"Renamed: {old_file_path} → {new_file_path}")

2. Reverse Conversion: Restore Original Filenames

This function will reverse the above process: it looks for files matching the Name_Ext.txt pattern, extracts the original name and extension, and renames them back (e.g., script_py.txt → script.py). It's safe to run on normal .txt files since it only targets files with an underscore before the final .txt.

def restore_from_txt(directory):
    """
    Recursively restore files renamed by convert_to_txt() back to their original names.
    Only processes files following the "originalName_originalExt.txt" pattern.
    
    Args:
        directory (str): Path to the target folder (including subfolders to process)
    """
    for foldername, _, filenames in os.walk(directory):
        for filename in filenames:
            # Skip files that aren't .txt or don't have an underscore (avoids breaking normal .txt files)
            if not (filename.endswith('.txt') and '_' in filename):
                continue
            
            # Split at the LAST underscore to handle original filenames with underscores (e.g., "my_script.py" → "my_script_py.txt")
            base_part, ext_part = filename.rsplit('_', 1)
            # Extract the original extension by removing the trailing ".txt"
            original_ext = ext_part.rsplit('.txt', 1)[0]
            # Build the original filename
            original_filename = f"{base_part}.{original_ext}"
            
            # Construct full paths
            old_file_path = os.path.join(foldername, filename)
            new_file_path = os.path.join(foldername, original_filename)
            
            # Rename back to original
            os.rename(old_file_path, new_file_path)
            print(f"Restored: {old_file_path} → {new_file_path}")

How to Use

  1. Run Forward Conversion:

    # Replace with your target directory path
    convert_to_txt("/home/your_username/documents/your_folder")
    

    This will handle all file types (.py, .ipynb, .csv, etc.) except .txt.

  2. Run Reverse Conversion:

    # Use the same directory path to restore files
    restore_from_txt("/home/your_username/documents/your_folder")
    

    This will revert only the files that were renamed by the first function.

Key Notes

  • Both functions work recursively, so they'll process every subfolder in your target directory.
  • Always back up your files before running bulk rename operations—better safe than sorry!
  • The reverse function won't touch normal .txt files (only those with the _Ext.txt pattern).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:07:36