R语言 将嵌套文件夹转换为原始矢量的嵌套列表,然后再转换回来

c9qzyr3d  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(132)

假设我们有一个如下定义的folder

folder <- tempfile()
dir.create(folder)
dir.create(file.path(folder, "subfolder"))
writeLines("hello", file.path(folder, "hello.txt"))
writeLines("world", file.path(folder, "subfolder", "world.txt"))

我想要一个具有以下结构的列表作为输出:

list(
  hello.txt = readBin(...),
  subfolder = list(
    world.txt = readBin(...)
  )
)

然后把它放回新的地方。

v1l68za4

v1l68za41#

这似乎做到了:

folder_to_list <- function(path) {
  if (!dir.exists(path)) return(readBin(path, "raw", file.info(path)$size))
  paths <- list.files(path, all.files = TRUE, no.. = TRUE)
  setNames(lapply(file.path(path, paths), folder_to_list), paths)
}

list_to_folder <- function(x, path) {
  dir.create(path)
  dirs <- names(Filter(is.list, x))
  files <- setdiff(names(x), dirs)
  for (file in files) writeBin(x[[file]], file.path(path, file))
  for (dir in dirs) list_to_folder(x[[dir]], file.path(path, dir))
}
x <- folder_to_list(folder)
x
#> $hello.txt
#> [1] 68 65 6c 6c 6f 0d 0a
#> 
#> $subfolder
#> $subfolder$world.txt
#> [1] 77 6f 72 6c 64 0d 0a
new_folder <- tempfile()
list_to_folder(x, new_folder)
list.files(new_folder, recursive = TRUE)
#> [1] "hello.txt"           "subfolder/world.txt"
readLines(file.path(new_folder, "hello.txt"))
#> [1] "hello"
readLines(file.path(new_folder, "subfolder", "world.txt"))
#> [1] "world"

创建于2023-06-21使用reprex v2.0.2

相关问题