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

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

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

  1. folder <- tempfile()
  2. dir.create(folder)
  3. dir.create(file.path(folder, "subfolder"))
  4. writeLines("hello", file.path(folder, "hello.txt"))
  5. writeLines("world", file.path(folder, "subfolder", "world.txt"))

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

  1. list(
  2. hello.txt = readBin(...),
  3. subfolder = list(
  4. world.txt = readBin(...)
  5. )
  6. )

然后把它放回新的地方。

v1l68za4

v1l68za41#

这似乎做到了:

  1. folder_to_list <- function(path) {
  2. if (!dir.exists(path)) return(readBin(path, "raw", file.info(path)$size))
  3. paths <- list.files(path, all.files = TRUE, no.. = TRUE)
  4. setNames(lapply(file.path(path, paths), folder_to_list), paths)
  5. }
  6. list_to_folder <- function(x, path) {
  7. dir.create(path)
  8. dirs <- names(Filter(is.list, x))
  9. files <- setdiff(names(x), dirs)
  10. for (file in files) writeBin(x[[file]], file.path(path, file))
  11. for (dir in dirs) list_to_folder(x[[dir]], file.path(path, dir))
  12. }
  1. x <- folder_to_list(folder)
  2. x
  3. #> $hello.txt
  4. #> [1] 68 65 6c 6c 6f 0d 0a
  5. #>
  6. #> $subfolder
  7. #> $subfolder$world.txt
  8. #> [1] 77 6f 72 6c 64 0d 0a
  1. new_folder <- tempfile()
  2. list_to_folder(x, new_folder)
  3. list.files(new_folder, recursive = TRUE)
  4. #> [1] "hello.txt" "subfolder/world.txt"
  5. readLines(file.path(new_folder, "hello.txt"))
  6. #> [1] "hello"
  7. readLines(file.path(new_folder, "subfolder", "world.txt"))
  8. #> [1] "world"

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

展开查看全部

相关问题