首页 > 解决方案 > 将 csv 文件移动到存档中的特定命名文件夹

问题描述

我在 Risk/Archive/ 文件夹中有 16 个具有特定人名的文件夹,我想将我的 Excel 文件(也包含特定人名)从 Risk/ 文件夹复制到与我正在使用的文件夹名称匹配的 Risk/archive/ 文件夹下面的代码,但这不是我想要完成的。

f = list.files('Risk/')

d = list.dirs('Risk/Archive')

if (length(f) > 0) {
      File = lapply(paste0('Risk/',f), function(i){
        x <- read.xlsx(i, sheet = 1, startRow=2, colNames = TRUE, check.names = FALSE, cols = c(1:73))
        file.copy(from=i, to='Risk/Archive/', 
        overwrite = TRUE, recursive = FALSE,copy.mode = TRUE)
    x})
  File <- do.call("rbind.data.frame", File)}

标签: r

解决方案


可能有更好的方法可以做到这一点,但如果我理解正确,我认为这应该可以解决问题:

# Get list of names of people
names <- list.dirs(path = "./Risk/Archive",
                   full.names = F,
                   recursive = F)

# Get list of files to copy
files <- list.files(path = "./Risk",
                    pattern = ".xlsx",
                    full.names = T)

# Loop through each name and move the file for that person
for(name in 1:length(names)){
  # Current name in loop
  cname <- names[name]
  # Get index of file that contains current name
  name.idx <- grep(files, pattern = cname)
  # Get file path for file that matches current name
  file.path <- files[name.idx]
  # Make file path for archive folder for current name
  name.path <- paste0("./Risk/Archive/", cname)
  # Copy file from "Risk" folder to "Archive" folder for current name
  file.copy(from = file.path,
            to = name.path,
            overwrite = T)
  # Remove original file after archiving
  file.remove(file.path)
  # Output message
  cat(paste0("Moved file for: ", cname, "\n"))
}

推荐阅读