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

如何在For Each循环中引用文件夹内同类型文件实现批量重命名

How to Reference Individual Files in a For Each Loop for Batch Renaming

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:06:50