如何在targets管道中处理tar_make后删除的file目标以同步目录
在targets管道中实现CSV文件目录同步(含删除同步)
要解决input目录CSV文件与output目录的双向同步(新增/修改复制、删除同步清理),核心是对比当前input文件列表与上一次tar_make运行时的input文件列表,针对性执行复制和删除操作。以下是具体实现方案:
核心实现思路
- 追踪当前input目录的CSV文件,记录文件的存在状态和修改时间
- 从targets元数据中读取上一次运行时的input文件列表
- 对比两个列表,区分出:
- 需要复制/覆盖的文件(新增或内容修改的input文件)
- 需要删除的output文件(已从input移除的文件对应的output副本)
- 将同步操作整合到targets管道中,确保每次
tar_make()都执行检查和清理
完整targets脚本示例
library(targets) library(fs) library(glue) # 定义目录路径 input_dir <- "input" output_dir <- "output" # 初始化目录(不存在则创建) dir_create(input_dir, recurse = TRUE) dir_create(output_dir, recurse = TRUE) # 1. 获取当前input目录的所有CSV文件路径(追踪文件变化) tar_target( current_input_paths, dir_ls(input_dir, regexp = "\\.csv$"), format = "file" # 自动追踪文件的创建、修改、删除 ) # 2. 获取上一次运行时的input文件列表(首次运行返回空向量) tar_target( previous_input_paths, { tryCatch( tar_read(current_input_paths, store = "_targets"), error = function(e) character(0) ) }, format = "rds", deployment = "main" # 强制每次运行都重新读取历史数据,不缓存 ) # 3. 计算需要执行的同步操作 tar_target( sync_actions, { # 筛选新增或修改的文件:当前存在但历史没有,或文件修改时间晚于output副本 new_files <- setdiff(current_input_paths, previous_input_paths) modified_files <- intersect(current_input_paths, previous_input_paths) modified_files <- modified_files[ file_mtime(current_input_paths) > file_mtime(path(output_dir, path_file(current_input_paths))) ] to_copy <- c(new_files, modified_files) # 筛选需要删除的output文件:历史存在但当前已删除的input文件对应的副本 to_delete <- path(output_dir, path_file(setdiff(previous_input_paths, current_input_paths))) to_delete <- to_delete[file_exists(to_delete)] # 过滤已不存在的文件,避免报错 list(to_copy = to_copy, to_delete = to_delete) }, depends_on = c(current_input_paths, previous_input_paths) ) # 4. 执行同步:复制新增/修改文件,删除已移除文件的副本 tar_target( sync_result, { # 复制文件到output目录(覆盖已存在的旧文件) if (length(sync_actions$to_copy) > 0) { file_copy(sync_actions$to_copy, output_dir, overwrite = TRUE) } # 删除output中对应的冗余文件 if (length(sync_actions$to_delete) > 0) { file_delete(sync_actions$to_delete) } # 返回同步结果,便于调试查看 list(copied_files = sync_actions$to_copy, deleted_files = sync_actions$to_delete) }, depends_on = sync_actions, format = "rds" )
关键细节说明
current_input_paths使用format="file",让targets自动追踪文件的创建、修改和删除状态,文件变化时会触发后续target重新运行previous_input_paths设置deployment="main",确保每次tar_make()都会重新读取上一次的历史文件列表,不会被缓存- 用
file_mtime检查文件修改时间,避免仅通过路径判断导致的内容修改不同步问题 - 对
to_delete做存在性检查,防止删除不存在的文件引发报错
测试验证步骤
- 首次运行
tar_make():input目录的所有CSV文件会被复制到output目录 - 删除input中的某个CSV文件,再次运行
tar_make():output中对应的文件会被自动删除 - 修改input中某个CSV的内容,再次运行
tar_make():output中的对应文件会被覆盖更新
内容的提问来源于stack exchange,提问作者Christian Million
相关产品推荐
相关产品推荐

