【问题标题】:Can R be utilized to automate file migration?可以利用 R 来自动化文件迁移吗?
【发布时间】:2019-06-04 20:57:17
【问题描述】:

根据一些回复,我对原始帖子进行了编辑以使其更加具体:)

问题 - 我想弄清楚如何自动化文件迁移。

这是目录“.../test”中文件结构的摘录

  • 011_433

  • 9087_345

  • new_files

文件夹 011_433 和 9087_345 中的文件具有一些字符串模式,例如文件名中包含“B_14”或“B_15”的文件。这些文件散布在文件夹中,因此具有“B_14”的文件不会仅驻留在一个文件夹中(具有其他模式的文件也是如此)。文件夹 new_files 是我希望将文件迁移到的位置,以便它们驻留在根据其模式命名的文件夹中,例如:

目录 ".../test/new_files" 将包含以下子目录:

  • B_14

  • B_15

每个文件夹将包含名称与文件夹名称匹配的字符串模式的文件。

这是我到目前为止所做的,它有效,但我真的不知道如何在此之外自动化它,因为文件模式名称没有任何押韵或理由。

library(filesstrings)

path <- "C:/my_directory/test/"
setwd(path)

#get a list of all files in test directory sub folders that match a specific #string pattern
B_14_ <- list.files(path, pattern = "_B-14", recursive = TRUE) 

#move all the files from test into their respective folder under 'new_files'
file.move(B_14_, "C:/my_directory/test/new_files/B_14"


#repeat for the next pattern....
B_15_ <- list.files(path, pattern = "_B-15", recursive = TRUE)
file.move(B_15_, "C:/my_directory/test/new_files/B_15"

#etc.

我的问题是我可以再自动化吗?如果我有所有字符串模式的列表,我可以以某种方式将其合并到其中吗?

感谢您的帮助!

【问题讨论】:

  • 是的,你可以用 R 做到这一点
  • 我不认为你希望每个文件去哪里特别清楚,但是看看 fs 包,它使文件路径的计算变得非常容易。
  • 到目前为止你有什么尝试?
  • 我已经更新了原始问题,希望得到一些更具体的回复@Stedy

标签: r file-transfer


【解决方案1】:

当然,这里还有一层抽象:

path <- "C:/my_directory/test/"
setwd(path)
patts = c("B-14", "B-15")
dirs = sub(pattern = "-", replacement = "_", x = patts, fixed = TRUE)

for (i in seq_along(patts)) {
  files <- list.files(path, pattern = paste0("_", patts[i]), recursive = TRUE) 
  file.move(files, paste0("C:/my_directory/test/new_files/", dirs[i]"))
}

【讨论】:

  • 这工作得很好,除了我现在遇到一个错误,指出:“file.move 错误(files, paste0("my_file_path", : Assertion on 'files' failed: file does not存在:'file_in_path'。是的,文件实际上存在于指定位置。
  • 查看 files(!file.exists(files)) 以查看 R 认为哪些文件不存在,并仔细检查。
猜你喜欢
  • 2012-02-24
  • 2019-12-18
  • 2012-03-27
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 2018-08-28
  • 2022-11-26
相关资源
最近更新 更多