如何用R将TXT指定的图片从目录及子目录复制到桌面文件夹
用R批量复制匹配指定名称的图片
实现步骤及代码
- 设定基础路径与目标文件夹
先定义资产根目录、目标文件名TXT路径,以及桌面的输出文件夹(不存在则自动创建)。
# 资产根目录 assets_root <- "/home/user/IAT/main/assets/" # 存放目标文件名的TXT路径,替换为你的实际路径 target_names_txt <- "/path/to/your/target_names.txt" # 桌面的目标文件夹,替换为你想存放的路径 dest_folder <- "/home/user/Desktop/target_images/" # 若目标文件夹不存在则创建 if (!dir.exists(dest_folder)) { dir.create(dest_folder, recursive = TRUE) }
- 读取目标文件名列表
读取TXT中的无扩展名文件名,转成字符向量用于后续匹配。
# 读取TXT文件(每行一个文件名) target_names <- readLines(target_names_txt) # 去除文件名可能带的空白字符 target_names <- trimws(target_names)
- 遍历samples文件夹并匹配复制
遍历资产目录下的所有顶层文件夹,拼接出对应的samples路径,扫描路径内的图片,匹配成功则复制到目标文件夹。
# 获取资产根目录下的所有顶层子文件夹 top_folders <- list.dirs(assets_root, recursive = FALSE, full.names = TRUE) # 逐个处理顶层文件夹 for (top_folder in top_folders) { # 拼接当前文件夹下的samples路径 samples_path <- file.path(top_folder, "images", "batch0001", "samples") # 确认samples路径存在再继续 if (dir.exists(samples_path)) { # 获取路径下所有png/jpg格式的图片完整路径 image_files <- list.files( path = samples_path, pattern = "\\.(png|jpg)$", full.names = TRUE, ignore.case = TRUE ) # 提取图片的无扩展名文件名 image_names <- tools::file_path_sans_ext(basename(image_files)) # 筛选出匹配目标名称的图片 match_idx <- which(image_names %in% target_names) # 复制匹配到的图片 if (length(match_idx) > 0) { file.copy( from = image_files[match_idx], to = dest_folder, overwrite = FALSE # 若目标文件夹已有同名文件,不覆盖;需覆盖则改为TRUE ) cat("从", samples_path, "复制了", length(match_idx), "张图片\n") } } }
注意事项
- 确保TXT文件每行仅含一个无扩展名文件名,无多余空格或空行。
- 若存在多个batch文件夹(如batch0002、batch0003),需修改代码中
batch0001部分,改用list.dirs遍历所有batch开头的子文件夹。 overwrite参数可根据需求调整,默认保留目标文件夹已有文件,避免误覆盖。
内容的提问来源于stack exchange,提问作者Wilson Souza
相关产品推荐
相关产品推荐

