2
$\begingroup$

Putting files into the wrong directory and then failing to remember where I put them is the bane of my existence. Consequently, I’d like to create a function that can create multiple file directories at once to keep things organized, or at least give the appearance of organization.

Assuming I have already created a number of directories say (all relative, of course):

dnames = {"SubD1", "SubD2", "SubD3"}

Using

SetDirectory[dnames[[n]]]

I can then refer to each directory giving n, in this case the values 1, 2, and 3

I wish then to create several subidrectories at once for each of these in order, say

{“SubDSub1”, “SubDSub2”,”SubDSub3”}

Hence I set

n=1;

and create my function (all in a single cell):

makeSubdirectory[x_] := SetDirectory[dnames[[n]]]; 
CreateDirectory[{"SubSubDir1","SubSubDir2","SubSubDir3"}];ResetDirectory[];n=n+1;

Which I then map to apply to each of the dnames

makeSubdirectory[n] /@ dnames

Unfortunately, this doesn’t work, but I’m not sure why. Since n is global, I believe it’s incremented, but I can only create the subdirectories in the first directory only, or so it seems. Since the value of x_ is not referred to there seems no reason to create a Module on this multiline function (perhaps not properly interpreted as a single line?) [I'm running V12.1.0.0 on a 64bit Windows system]

Can anyone explain how to create multiple subdirectories mapped across multiple directories?

Sadly, old procedural paradigms die hard for old programmers. I suspect there must be a better more "functional" equivalent here.

$\endgroup$
1
  • $\begingroup$ SetDirectory only changes the working directory, that is, the directory your exported files without a specific destination will end up in & from where you can import without specifying a source. $\endgroup$ Dec 18, 2020 at 9:12

1 Answer 1

3
$\begingroup$

Try e.g.:

fullpath = "d:/tmp/";
dirs = Table[fullpath <> "dir" <> ToString[i], {i, 2}];
fils = Table["/fil" <> ToString[i], {i, 2}];
Outer[(If[! DirectoryQ[#1], CreateDirectory[#1]]; 
   CreateFile[#1 <> #2]) &, dirs, fils]
$\endgroup$
1
  • $\begingroup$ What I needed, except that the fils needed to be directories themselves. Swapping out CreateDirectory for CreateFile and all is good. Thanks for alerting me to the usefulness of Outer, which provides the "functional approach" I was seeking. $\endgroup$ Dec 19, 2020 at 0:48

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.