logo

How to Recursively Retrieve a List of Files under a Specific Path in Julia 📂Julia

How to Recursively Retrieve a List of Files under a Specific Path in Julia

Code

walkdir

julia> walkdir("D:\\U\\B")
Channel{Tuple{String, Vector{String}, Vector{String}}}(0) (1 item available)

julia> collect(walkdir("D:\\U\\B"))
2-element Vector{Tuple{String, Vector{String}, Vector{String}}}:
 ("D:\\U\\B", ["b"], ["alpha.txt", "beta.txt"])
 ("D:\\U\\B\\b", [], ["m.txt"])

walkdir is a built-in function that explores all files under a given path. By itself, it is an iterator containing tuples with file information, which can be accessed as an array through functions like collect.

However, dealing with this function without any knowledge can be quite tricky, so let’s refer to the following trick for easier use.

Trick

alt text

If a specific path is referred to as tgt, the file list under this path can be recursively obtained with the following command1.

julia> [(joinpath.(root, files) for (root, dirs, files) in walkdir("tgt"))...;]
6-element Vector{String}:
 "D:\\U\\A\\x.txt"
 "D:\\U\\A\\y.txt"
 "D:\\U\\A\\zz.bmp"
 "D:\\U\\B\\alpha.txt"
 "D:\\U\\B\\beta.txt"
 "D:\\U\\B\\b\\m.txt"

Environment

  • OS: Windows
  • julia: v1.11.1