如何将文件夹内文件批量重命名为[原名_原后缀].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:
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}")
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
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.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
.txtfiles (only those with the_Ext.txtpattern).
内容的提问来源于stack exchange,提问作者Akash Dubey

