将目录树表示为递归列表 [英] Representing a directory tree as a recursive list

查看:95
本文介绍了将目录树表示为递归列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持执行某项任务.我想要的是一个给定目录路径的函数,该函数将返回递归列表作为输出.

I am stuck with a certain task. What I want is a function that, given a directory path, would return a recursive-list as an output.

输出形式应为myList $ dir $ subdir $ subdir $ fullFilePath

The output should be of the form myList$dir$subdir$subdir$fullFilePath

所以基本上我想将目录树表示为某个列表.我获得了所有文件,并获得了每个文件的所有子目录,但是对于如何将它们全部放入具有多个级别的列表中,我还是一窍不通.

So basically I want to represent a directory tree as a certain list. I obtain all the files, get all the subdirectories for each of the file, but I am stuck as to how to throw it all into a list with multiple levels.

推荐答案

以下是使用递归的解决方案:

Here is a solution using recursion:

tree.list <- function(file.or.dir) {
    isdir <- file.info(file.or.dir)$isdir
    if (!isdir) {
        out <- file.or.dir
    } else {
        files <- list.files(file.or.dir, full.names   = TRUE,
                                         include.dirs = TRUE)
        out <- lapply(files, tree.list)
        names(out) <- basename(files)
    }
    out
}

我已经在一个小目录上对其进行了测试

I have tested it here on a small directory

test.dir <- tree.list("./test")
test.dir
# $a
# $a$`1.txt`
# [1] "./test/a/1.txt"
# 
# $a$aa
# $a$aa$`2.txt`
# [1] "./test/a/aa/2.txt"
# 
# $b
# $b$`3.txt`
# [1] "./test/b/3.txt"

如果这对于您的需求而言太慢了,我会考虑使用recursive = TRUE将所有文件读取到对list.files的单个调用中,然后进行一些解析.

If this is too slow for your needs, I would consider reading all the files into a single call to list.files with recursive = TRUE then do a bit of parsing.

这篇关于将目录树表示为递归列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆