I am looking to make graphics of a folder hierarchy, and this old post was very helpful. However, this method gives the whole file path for each node, which makes a complete mess in the directory I want to use it. It must not be too tricky, but I cannot figure out how to get just the last part of the path from each node of the tree structure.

In the abstract, if I have tree = a[b[c,d,e],g[h]], I believe I want some way of performing F[tree] = F[a][F[b][F[c],F[d],F[e]],F[g][F[h]]]. I am struggling to implement.

In the concrete, I mildly adapted the code from the linked question above:

readDir[currentDirectory_, 0] := FileNameTake[currentDirectory];

readDir[currentDirectory_, level_] := 
Module[{}, SetDirectory[currentDirectory];
joinedFiles = 
FileNameJoin[{currentDirectory, #}] & /@ FileNames[];
unjoinedFiles = FileNames[];

(*do a logical test;
if the thing in a directory is a directory,*)
perFile[file_] := 
 file @@ readDir[file, level - 1],(*true*)Sequence @@ {}];(*false*)
perFile /@ joinedFiles];

treeDir[dir_] := TreeForm[dir @@ readDir[dir, 11]]


This yields the nice tree, but with the less-nice filepaths built in: enter image description here

Can I either: (1) apply a function to the nested expression that gives me the first graphic, or (2) rewrite the generative code in another way, to give me the following from the directory input:

enter image description here

  • 1
    $\begingroup$ Try e.g.: treeDir[dir_] := TreeForm[dir @@ (readDir[dir, 11] /. _String :> Unique[])] $\endgroup$ Jan 16, 2021 at 12:15

1 Answer 1


To expand on Daniel's comment, here is one way:

treeDir[dir_] := TreeForm[
  dir @@ (readDir[dir, 11] /. s_String[] :> s /. name_String :> FileNameTake[name])


treeDir["C:\\\\Program Files\\\\JetBrains\\\\IntelliJ IDEA 2020.2"]

Mathematica graphics

There are two replacement rules added in this example:

s_String[] :> s takes care of the [] in filename[] that appears in the original code.

name_String :> FileNameTake[name] selects the last component in the file path as the name.

  • 2
    $\begingroup$ If a Graph[] is desired: treeDir[dir_] := ExpressionGraph[dir @@ (readDir[dir, 11] /. s_String[] :> s /. name_String :> FileNameTake[name]), PlotTheme -> "ClassicDiagram", VertexLabels -> Placed[Automatic, Center]] $\endgroup$ Jan 17, 2021 at 2:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.