使用 R 将文件复制粘贴到具有匹配名称的文件夹
Copy-paste files to folders that have matching names using R
我正在尝试将文件复制到具有匹配文件名的各种文件夹。
这是文件名的摘录:
20201026_ABCD.txt
20201026_XYZ.txt
20201027_ABCD.txt
20201027_POR.txt
20201028_ABCD.txt
20201028_PQR.txt
我想创建仅包含上述文件中的日期组件的文件夹。我已经根据下面的代码成功地做到了这一点:
setwd("C:/Projects/TEST")
library(stringr)
filenames<-list.files(path = "C:/Projects/TEST", pattern = NULL)
#create a variable that contains all the desired filenames
foldernames.unique<-unique(str_extract(filenames,"[0-9]{1,8}"))
#create folders based on this variable
foldernames.unique<-paste("dates/",foldernames.unique,sep='')
lapply(foldernames.unique,dir.create,recursive = TRUE)
现在,如何将 20201026_ABCD.txt and 20201026_XYZ.txt
复制到文件夹 20201026
,等等?
现在您只需要使用file.rename
来移动文件。首先,我将稍微更改一下以捕获 non-unique 文件夹名称,这样我就不必重新命名它们。这个怎么样
srcfolder <- "C:/Projects/TEST"
filenames <- list.files(path = srcfolder, pattern = NULL)
#create a variable that contains the desired foldername for each file
foldernames <- file.path("dates", str_extract(filenames,"[0-9]{1,8}"))
foldernames.unique <- unique(foldernames)
#create folders based on unique values of variable
lapply(foldernames.unique, dir.create, recursive = TRUE)
# Now move files
file.rename(file.path(srcfolder, filenames), file.path(foldernames, filenames))
我们只是用 file.path
构建文件名,这比 paste()
更健壮一点
我正在尝试将文件复制到具有匹配文件名的各种文件夹。
这是文件名的摘录:
20201026_ABCD.txt
20201026_XYZ.txt
20201027_ABCD.txt
20201027_POR.txt
20201028_ABCD.txt
20201028_PQR.txt
我想创建仅包含上述文件中的日期组件的文件夹。我已经根据下面的代码成功地做到了这一点:
setwd("C:/Projects/TEST")
library(stringr)
filenames<-list.files(path = "C:/Projects/TEST", pattern = NULL)
#create a variable that contains all the desired filenames
foldernames.unique<-unique(str_extract(filenames,"[0-9]{1,8}"))
#create folders based on this variable
foldernames.unique<-paste("dates/",foldernames.unique,sep='')
lapply(foldernames.unique,dir.create,recursive = TRUE)
现在,如何将 20201026_ABCD.txt and 20201026_XYZ.txt
复制到文件夹 20201026
,等等?
现在您只需要使用file.rename
来移动文件。首先,我将稍微更改一下以捕获 non-unique 文件夹名称,这样我就不必重新命名它们。这个怎么样
srcfolder <- "C:/Projects/TEST"
filenames <- list.files(path = srcfolder, pattern = NULL)
#create a variable that contains the desired foldername for each file
foldernames <- file.path("dates", str_extract(filenames,"[0-9]{1,8}"))
foldernames.unique <- unique(foldernames)
#create folders based on unique values of variable
lapply(foldernames.unique, dir.create, recursive = TRUE)
# Now move files
file.rename(file.path(srcfolder, filenames), file.path(foldernames, filenames))
我们只是用 file.path
构建文件名,这比 paste()