5

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_] := If[DirectoryQ[file],(condition) file @@ readDir[file, level - 1],(true)Sequence @@ {}];(false) perFile /@ joinedFiles];

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

treeDir["/Users/vironevaeh/a"]

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

KBL
  • 643
  • 3
  • 10

1 Answers1

5

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

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

Example:

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.

C. E.
  • 70,533
  • 6
  • 140
  • 264
  • 2
    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]] – J. M.'s missing motivation Jan 17 '21 at 02:36