乐天一族 2025-05-24 00:35 采纳率: 0%
浏览 6

请教文件处理批量文件路径前移

向各位大拿请教,一点微不足道的小问题
情况是A文件夹下有B1~B298名字都不同的子文件夹,每个B文件夹下有同名的C文件夹,每个C文件夹内有不同的文件。

现在的需求是将每个C文件夹内的文件转移到各个C文件夹对应的B文件夹里,再统一删除C文件夹(删除这步这个会的)。

也就是说把B1里C文件夹里的文件转移到B1,B2里C文件夹里的文件转移到B2,这重复298次的操作有没有什么神奇代码bat脚本能一键搞定,请教

  • 写回答

5条回答 默认 最新

  • 阿里嘎多学长 2025-05-24 00:35
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    文件处理批量文件路径前移

    你想将每个C文件夹内的文件转移到各个C文件夹的上一级目录(即B文件夹),对吧?可以使用 Python 的 osshutil 模块来实现。

    以下是一个示例代码:

    import os
    import shutil
    
    # 设置要处理的文件夹路径
    root_dir = '/path/to/A'
    
    # 遍历每个B文件夹
    for b_dir in os.listdir(root_dir):
        if os.path.isdir(os.path.join(root_dir, b_dir)):
            # 遍历每个C文件夹
            for c_dir in os.listdir(os.path.join(root_dir, b_dir)):
                if os.path.isdir(os.path.join(root_dir, b_dir, c_dir)):
                    # 将C文件夹内的文件转移到上一级目录
                    for file in os.listdir(os.path.join(root_dir, b_dir, c_dir)):
                        shutil.move(os.path.join(root_dir, b_dir, c_dir, file), os.path.join(root_dir, b_dir, file))
    

    这个代码遍历每个B文件夹,然后遍历每个C文件夹,最后将C文件夹内的文件转移到上一级目录。

    请注意,你需要将 root_dir 设置为你的实际文件夹路径。

    如果你想使用 PowerShell,可以使用以下命令:

    Get-ChildItem -Path A -Recurse -Directory | ForEach-Object {
        $c_dir = Join-Path -Path $_.FullName -ChildPath $_.Name
        Get-ChildItem -Path $c_dir -Recurse | ForEach-Object {
            $file = Join-Path -Path $c_dir -ChildPath $_.Name
            Move-Item -Path $file -Destination (Join-Path -Path $_.Directory -ChildPath $_.BaseName)
        }
    }
    

    这个命令遍历每个B文件夹,然后遍历每个C文件夹,最后将C文件夹内的文件转移到上一级目录。

    评论

报告相同问题?

问题事件

  • 创建了问题 5月24日