如何批量重命名2000个TXT文件?基于指定行内字符串
Batch Rename TXT Files Using Specific Lines from Their Content
Hey Tom, I feel your pain—those generic tutorials can be totally overwhelming when you just need a straight solution for your specific case. Let's get those 2000 TXT files renamed properly, using the exact strings from lines 56 and 66 you mentioned. Here's a step-by-step approach with a simple Python script that does all the heavy lifting:
Step 1: Write the Script
Open any text editor (Notepad, Sublime Text, VS Code—whichever you have handy) and paste this code:
import os # Replace this with the actual folder path where your TXT files live target_folder = r"C:\Path\To\Your\TXT\Files" # Loop through every file in the target folder for file_name in os.listdir(target_folder): # Only process .txt files if file_name.lower().endswith(".txt"): full_file_path = os.path.join(target_folder, file_name) try: # Open the file and read all lines with open(full_file_path, 'r', encoding='utf-8') as txt_file: all_lines = txt_file.readlines() # Grab the 56th line (Python counts from 0, so index 55 is line 56) line_56 = all_lines[55].strip() # Extract the last quoted string (split by quotes, take the second-last item) id_from_line56 = line_56.split('"')[-2] # Grab the 66th line (index 65) line_66 = all_lines[65].strip() # Extract the last quoted string here too id_from_line66 = line_66.split('"')[-2] # Build your new filename (adjust the separator if you want something other than "_") new_file_name = f"{id_from_line56}_{id_from_line66}.txt" new_full_path = os.path.join(target_folder, new_file_name) # Rename only if the new name is different from the original if new_full_path != full_file_path: os.rename(full_file_path, new_full_path) print(f"Renamed: {file_name} → {new_file_name}") else: print(f"Skipped {file_name}: new name matches original") except Exception as error: print(f"Problem with {file_name}: {str(error)}")
Step 2: Tweak the Script for Your Setup
- Update the folder path: Replace
r"C:\Path\To\Your\TXT\Files"with the actual path to your folder of TXT files. Therbefore the quotes ensures spaces or special characters in the path work correctly. - Adjust the filename format: If you don't want an underscore between the two IDs, change
f"{id_from_line56}_{id_from_line66}.txt"to something likef"{id_from_line56}-{id_from_line66}.txt"or any other separator that fits your needs.
Step 3: Run the Script
- Save the file with a
.pyextension (likerename_my_txts.py). - If you don't have Python installed yet, grab it from the official site (make sure to check "Add Python to PATH" during installation—it makes running scripts way easier).
- Open Command Prompt (Windows) or Terminal (Mac/Linux), navigate to the folder where you saved the script, and run:
python rename_my_txts.py
Critical Pre-Run Notes
- Backup first!: Always make a copy of all your TXT files before running the script. It's a simple step that saves you from headaches if something unexpected happens.
- Check file encoding: If your TXT files use a non-UTF-8 encoding (like GBK for Chinese text), change
encoding='utf-8'in theopen()function to the correct encoding. - Verify line counts: Double-check that every TXT file has at least 66 lines. If any file is shorter, the script will throw an error (it'll print which file has the issue so you can fix it manually).
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

