5
$\begingroup$

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

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

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.

$\endgroup$
1
  • 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$ – J. M.'s ennui Jan 17 at 2:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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