如何将嵌套文件夹转换为嵌套原始向量列表并还原?
解决方案
1. 将文件夹结构转换为嵌套列表
写一个递归函数遍历目标文件夹:遇到文件就用readBin读取为原始二进制数据,遇到子文件夹则递归生成嵌套列表。
dir_to_list <- function(path) { entries <- list.files(path, full.names = TRUE, include.dirs = TRUE) names <- basename(entries) result <- lapply(seq_along(entries), function(i) { entry <- entries[i] if (file.info(entry)$isdir) { dir_to_list(entry) } else { readBin(entry, what = "raw", n = file.info(entry)$size) } }) names(result) <- names result }
2. 将嵌套列表还原为文件夹结构
同样用递归函数处理列表:遇到子列表就创建对应文件夹,遇到二进制数据则写入目标文件。
list_to_dir <- function(x, root_path) { if (!dir.exists(root_path)) dir.create(root_path, recursive = TRUE) for (name in names(x)) { current_path <- file.path(root_path, name) if (is.list(x[[name]])) { dir.create(current_path, recursive = TRUE) list_to_dir(x[[name]], current_path) } else { writeBin(x[[name]], current_path) } } }
测试示例
用你提供的文件夹结构验证功能:
# 创建测试文件夹 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")) # 转换为嵌套列表 folder_list <- dir_to_list(folder) # 查看结构 str(folder_list) #> List of 2 #> $ hello.txt : raw [1:6] 68 65 6c 6c 6f 0a #> $ subfolder:List of 1 #> ..$ world.txt: raw [1:6] 77 6f 72 6c 64 0a # 还原到新路径 new_folder <- tempfile() list_to_dir(folder_list, new_folder) # 验证还原结果 readLines(file.path(new_folder, "hello.txt")) #> [1] "hello" readLines(file.path(new_folder, "subfolder", "world.txt")) #> [1] "world"
说明
- 用
readBin/writeBin处理文件能兼容所有类型(不只是文本),因为直接操作原始二进制数据。 - 递归逻辑支持任意深度的嵌套文件夹结构。
内容的提问来源于stack exchange,提问作者moodymudskipper
相关产品推荐
相关产品推荐

