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

如何用R函数从6000个PDF中迁移指定300个至其他文件夹

R函数实现指定PDF文件迁移方案

核心思路

基于R基础文件操作函数,通过指定目标文件名列表,批量检查源文件存在性并完成复制迁移,无需额外依赖包。

函数实现

move_specified_pdfs <- function(source_dir, target_dir, target_files) {
  # 确保目标文件夹存在,不存在则创建
  if (!dir.exists(target_dir)) {
    dir.create(target_dir, recursive = TRUE)
    message(paste("已创建目标文件夹:", target_dir))
  }
  
  # 遍历目标文件列表,逐一处理
  for (file in target_files) {
    source_path <- file.path(source_dir, file)
    target_path <- file.path(target_dir, file)
    
    # 检查源文件是否存在
    if (file.exists(source_path)) {
      # 复制文件,默认不覆盖已存在文件,可修改overwrite参数
      file.copy(from = source_path, to = target_path, overwrite = FALSE)
      message(paste("已迁移:", file))
    } else {
      warning(paste("源文件不存在,跳过:", file))
    }
  }
  
  message("迁移任务完成")
}

参数说明

  • source_dir: 字符型,源PDF文件夹的完整路径(如"C:/pdfs/source"或"/home/user/pdfs/source")
  • target_dir: 字符型,目标文件夹的完整路径(迁移后文件存放位置)
  • target_files: 字符型向量,包含所有需要迁移的PDF文件名(必须带.pdf后缀,如c("file1.pdf", "report_2024.pdf"))

使用示例

  1. 定义目标文件列表:
    如果文件名存储在CSV文件中(比如target_files.csv,第一列为文件名),可读取:

    target_files <- read.csv("target_files.csv", header = FALSE, stringsAsFactors = FALSE)[,1]
    

    或者直接手动定义:

    target_files <- c("sample1.pdf", "sample2.pdf", "sample3.pdf") # 替换为你的300个文件名
    
  2. 调用迁移函数:

    move_specified_pdfs(
      source_dir = "C:/my_pdfs/all_pdfs",
      target_dir = "C:/my_pdfs/selected_pdfs",
      target_files = target_files
    )
    

注意事项

  • 路径格式:Windows系统建议用正斜杠/或双反斜杠\\;Linux/macOS用正斜杠/
  • 大小写敏感:Linux/macOS系统下文件名区分大小写,确保列表中的文件名与源文件完全匹配
  • 覆盖设置:如果需要覆盖目标文件夹中已存在的同名文件,将函数中的overwrite = FALSE改为overwrite = TRUE

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:30:48