我想从源文件夹中分类一堆图片,并根据其创建日期移动它们。因此,如果在2017-10-31上创建了一个文件,它将把图片移动到2017的父文件夹中,并移动到“ 2017-10-31”子文件夹中。如果该文件夹不存在,则应创建它。
我使用以下内容创建了文件创建日期和年份的数据列表。
files_tmp <- dir("C:/Users/.../pictures/",
full.names = TRUE)
filedate <-
as.data.frame(file.info(files_tmp)$ctime)
names(filedate)[1] <- "date"
pics <- filedate %>%
mutate (createDate = format(date, "%Y-%m-%d"),
year = format(date, "%Y"))
答案 0 :(得分:0)
您只需要正确设置数据即可。然后,将文件移动到适当的文件夹很简单。查看代码中的注释。
# create some fake data
cat("2017-01-01", file = "2017-01-01.txt")
cat("2018-05-11", file = "2018-05-11.txt")
cat("2018-09-09", file = "2018-09-09.txt")
# fetch all files - here I'm using to find exact dates and your method may vary
xy <- list.files(pattern = "\\d{4}-\\d{2}-\\d{2}\\.txt")
# prepare variables that will create (sub)folders
# having things in Date form makes extraction of year easy (and safe)
xy <- data.frame(file = xy, date = as.Date(gsub("\\.txt", "", xy)), stringsAsFactors = FALSE)
xy$path <- sprintf("./%s/%s", format(xy$date, "%Y"), xy$date)
# check that folder(s) exist
subfolders <- as.character(unique(xy$path))
# create those that do not exist
cs <- xy[!sapply(subfolders, FUN = dir.exists), ]
# if there's no data, it means all appropriate folders are already created
if (nrow(cs) == 0) {
message("All folders already exist.")
} else {
sapply(cs$path, dir.create, recursive = TRUE)
}
# prepare paths where to move files to
xy$dest_to <- sprintf("%s/%s", xy$path, xy$file)
# execute the final move
mapply(FUN = function(x, y) {
message(sprintf("Moving file %s to %s", x, y))
file.rename(from = x, to = y)
}, x = xy$file, y = xy$dest_to)