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

Windows下通过PowerShell、Python或R批量移动指定文件夹的方法

Windows下批量移动txt列表内目录的实现方法

三种工具都可以实现,以下是可直接运行的代码,均会自动处理txt路径中带的双引号、自动创建不存在的目标目录,且会将整个文件夹(含所有子目录、文件)完整移动。


PowerShell 方案(无需额外安装环境,Windows原生支持)

读取txt路径列表直接用Get-Content即可实现,之前使用的Copy-Item命令不需要提前枚举所有子项,直接对目录操作加-Recurse参数即可。移动操作使用Move-Item效率更高,不需要单独遍历文件。

  1. 将代码中两个配置变量替换为自己的实际路径
  2. 直接在PowerShell中运行即可
# 配置项
$pathListFile = "C:\实际路径\你的目录列表txt文件.txt"
$targetDir = "C:\Path\to\new\directory\"

# 目标目录不存在则自动创建
if (-not (Test-Path $targetDir -PathType Container)) {
    New-Item -ItemType Directory -Path $targetDir | Out-Null
}

# 逐行读取路径,处理引号后执行移动
Get-Content $pathListFile | ForEach-Object {
    $source = $_.Trim().Trim('"')
    if ($source -and (Test-Path $source -PathType Container)) {
        Move-Item -Path $source -Destination $targetDir -Recurse -Force
    }
}

Python 方案

使用Python标准库即可实现,无需安装第三方依赖,跨盘符兼容性好:

import os
import shutil

# 配置项
path_list_file = r"C:\实际路径\你的目录列表txt文件.txt"
target_dir = r"C:\Path\to\new\directory\"

# 自动创建目标目录
os.makedirs(target_dir, exist_ok=True)

# 读取路径并移动
with open(path_list_file, "r", encoding="utf-8") as f:
    for line in f:
        source = line.strip().strip('"')
        if source and os.path.isdir(source):
            dir_name = os.path.basename(source.rstrip("/\\"))
            shutil.move(source, os.path.join(target_dir, dir_name))

R 方案

之前用file.copy返回FALSE,核心原因是处理目录时没有加recursive=TRUE参数,且跨盘符移动时file.rename会失效,以下代码兼容同盘/跨盘移动:

# 配置项
path_list_file <- "C:/实际路径/你的目录列表txt文件.txt"
target_dir <- "C:/Path/to/new/directory/"

# 自动创建目标目录
dir.create(target_dir, recursive = TRUE, showWarnings = FALSE)

# 读取路径并移动
path_list <- readLines(path_list_file, warn = FALSE)
for (p in path_list) {
  source <- trimws(gsub('"', '', p))
  if (nchar(source) > 0 && dir.exists(source)) {
    dir_name <- basename(sub("[/\\]+$", "", source))
    dest <- file.path(target_dir, dir_name)
    # 先尝试直接改名(同盘移动速度快),失败则走复制+删除逻辑兼容跨盘
    if (!file.rename(source, dest)) {
      file.copy(source, dest, recursive = TRUE, overwrite = TRUE)
      unlink(source, recursive = TRUE, force = TRUE)
    }
  }
}

操作提示:首次测试时可以把移动命令替换为复制命令(PowerShell用Copy-Item、Python用shutil.copytree、R用file.copy),确认目标目录下文件结构正确后再执行移动,避免误操作。

内容的提问来源于stack exchange,提问作者yakumo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:15:11