如何在For Each循环中引用文件夹内同类型文件实现批量重命名
Alright, since you’ve already got the core renaming logic sorted out, let’s cut straight to the part you care about: how to reference each individual file in a For Each loop across some common programming/scripting languages. Here’s how it works in a few popular options:
Python (Modern, Clean Approach)
Using pathlib (built-in, path-handling made easy):
from pathlib import Path # Set your target folder and file type (e.g., ".png") target_folder = Path("/path/to/your/folder") file_extension = ".png" counter = 1 # Loop through every file matching the extension for file in target_folder.glob(f"*{file_extension}"): # This `file` variable is your individual file reference (the "X" in your example) # Generate the new IMG### filename with leading zeros new_name = f"IMG{counter:03d}{file_extension}" # Rename the file (handles path formatting automatically) file.rename(target_folder / new_name) counter += 1
In this loop, file is a Path object that represents each matching file—this is exactly the individual item you need to work with.
C# (.NET)
Using standard System.IO classes:
using System.IO; class BatchRenamer { static void Main() { string folderPath = @"C:\your\target\folder"; string fileExt = ".jpg"; int counter = 1; // Enumerate all files with the target extension foreach (string filePath in Directory.EnumerateFiles(folderPath, $"*{fileExt}")) { // `filePath` is the full path to each individual file (your "X") FileInfo file = new FileInfo(filePath); string newFileName = $"IMG{counter:03d}{fileExt}"; // Rename the file file.MoveTo(Path.Combine(folderPath, newFileName)); counter++; } } }
Here, filePath (or the FileInfo object file we create from it) is your reference to each single file in the foreach loop.
PowerShell (Quick Scripting)
Perfect for one-off tasks without compiling code:
$folderPath = "C:\your\folder\path" $fileExt = ".gif" $counter = 1 # Pipeline-style loop Get-ChildItem -Path $folderPath -Filter "*$fileExt" | ForEach-Object { # The `$_` variable represents the current individual file (your "X") $newFileName = "IMG{0:D3}{1}" -f $counter, $fileExt Rename-Item -Path $_.FullName -Destination (Join-Path $folderPath $newFileName) $counter++ }
If you prefer a traditional loop structure:
$files = Get-ChildItem -Path $folderPath -Filter "*$fileExt" foreach ($file in $files) { # `file` is your individual file reference here $newFileName = "IMG{0:D3}{1}" -f $counter, $fileExt Rename-Item -Path $file.FullName -Destination (Join-Path $folderPath $newFileName) $counter++ }
内容的提问来源于stack exchange,提问作者Christian Brewer

