使用R将多个文件从多个文件夹复制到单个文件夹
嘿,我想问一下如何使用R语言将多个文件从多个文件夹复制到单个文件夹 假设有三个文件夹:使用R将多个文件从多个文件夹复制到单个文件夹,r,file-manipulation,R,File Manipulation,嘿,我想问一下如何使用R语言将多个文件从多个文件夹复制到单个文件夹 假设有三个文件夹: 桌面/文件夹\任务/子任务/ 桌面/文件夹/任务/子任务/ 桌面/文件夹\u C/任务/子任务/ 在每个sub_任务文件夹中,都有多个文件。我想复制sub_任务文件夹中的所有文件,并将它们粘贴到桌面上的一个新文件夹中(让我们将这个新文件夹命名为“all_sub_任务”)。有人能告诉我如何在R中使用循环或应用函数吗?提前谢谢 这里有一个R解决方案 # Manually enter the directories
# Manually enter the directories for the sub tasks
my_dirs <- c("desktop/folder_A/task/sub_task/",
"desktop/folder_B/task/sub_task/",
"desktop/folder_C/task/sub_task/")
# Alternatively, if you want to programmatically find each of the sub_task dirs
my_dirs <- list.files("desktop", pattern = "sub_task", recursive = TRUE, include.dirs = TRUE)
# Grab all files from the directories using list.files in sapply
files <- sapply(my_dirs, list.files, full.names = TRUE)
# Your output directory to copy files to
new_dir <- "all_sub_task"
# Make sure the directory exists
dir.create(new_dir, recursive = TRUE)
# Copy the files
for(file in files) {
# See ?file.copy for more options
file.copy(file, new_dir)
}
#手动输入子任务的目录
my_dirs此代码应该可以工作。此函数获取一个目录(例如桌面/文件夹A/task/sub\u task/
),并将其中的所有内容复制到第二个目录。当然,您可以使用循环或应用程序一次使用多个目录,因为第二个值是固定的sapply(froms,copyEverything,to)
复制所有内容,谢谢。我想问一下,既然有很多文件夹(不仅仅是文件夹a、B和C),是否有一种方法可以使用循环函数来创建我的目录。键入每个路径将是一项相当艰巨的任务。for(my_dirs中的dir){dir.create(dir,recursive=TRUE)}
?但此代码不创建my_dirs。我知道我可以使用list.files在桌面上列出文件夹的名称。但我不知道如何使用循环来粘贴每个文件夹名称,以创建“桌面/(文件夹名称)/任务/子任务/”列表。例如,在您的评论中,my_dirs Oops-您可以尝试list.files(“desktop”,pattern=“subtask”,recursive=TRUE,include.dirs=TRUE)
而不是list.dirs
-它仍应列出目录。是否有方法将具有重复文件名的文件复制到一个目录中,并通过自动重命名重复文件来保留两个文件?
copyEverything <- function(from, to){
# We search all the files and directories
files <- list.files(from, r = T)
dirs <- list.dirs(from, r = T, f = F)
# We create the required directories
dir.create(to)
sapply(paste(to, dirs, sep = '/'), dir.create)
# And then we copy the files
file.copy(paste(from, files, sep = '/'), paste(to, files, sep = '/'))
}