udibehar
(Ehud Behar)
February 12, 2022, 11:27am
1
I want to set the current working directory for my session with SetDirectory.
Suppose I have a directory called MyNewFolder located in the default “documents” directory. On Mac it is located in
/Users/my_user_name/Documents/MyNewFolder
How can I set this directory as the working document using $UserDocumentsDirectory?
Of course I can do
SetDirectory["/Users/my_user_name/Documents/" <> "MyNewFolder"]
But to make this expression more user-wide, I want a command like
SetDirectory[$UserDocumentsDirectory <> "MyNewFolder"]
But, of course, it doesn’t work.
Any idea for how to do that?
hansmilton
(Hans Milton)
February 12, 2022, 2:21pm
2
By default (at least on Windows 10) the current directory is already set to $UserDocumentsDirectory. Then you can just go ahead like this:
In[1]:= $UserDocumentsDirectory
Out[1]= "C:\\Users\\HM\\Documents"
In[2]:= Directory[]
Out[2]= "C:\\Users\\HM\\Documents"
In[3]:= SetDirectory["MyNewFolder"]
Out[3]= "C:\\Users\\HM\\Documents\\MyNewFolder"
In[4]:= Directory[]
Out[4]= "C:\\Users\\HM\\Documents\\MyNewFolder"
A more robust way is to do it in two steps:
In[1]:= SetDirectory["C:\\Any Wild Folder"]
Out[1]= "C:\\Any Wild Folder"
In[2]:= Directory[]
Out[2]= "C:\\Any Wild Folder"
In[3]:= SetDirectory[$UserDocumentsDirectory]; SetDirectory["MyNewFolder"]
Out[3]= "C:\\Users\\HM\\Documents\\MyNewFolder"
In[4]:= Directory[]
Out[4]= "C:\\Users\\HM\\Documents\\MyNewFolder"
udibehar
(Ehud Behar)
February 12, 2022, 3:04pm
3
I see.
So I can do it in one line with
SetDirectory[$UserDocumentsDirectory]; SetDirectory["MyNewFolder"]
Thanks.
hansmilton
(Hans Milton)
February 12, 2022, 3:10pm
4
That is right. I just edited my post (adding “A more robust way …”), before I saw your reply.
Hi Ehud
What about:
SetDirectory@FileNameJoin[{$UserDocumentsDirectory, "MyNewFolder"}]
Robert
dlkeith
(David Keith)
February 12, 2022, 10:39pm
6
When starting a new project I usually want the notebook, any required files, and any output to reside in the same project directory. After saving the notebook to the project directory I include this SetDirectory[] as a first cell in the notebook:
SetDirectory[NotebookDirectory[]]
iwilliams
(Ian Williams)
February 13, 2022, 10:57am
7
Hi David,
I often use this exact same approach. But it’s a bit of a pain having to include the cell in pretty much each and every NB. So this discussion got me thinking about whether there’s a more convenient solution. What I’ve come up with is setting the value of CellProlog to SetDirectory[NotebookDirectory[]]. This can be done via the Options Inspector (Command-Shift-O on a Mac) and can be set at either the cell, notebook or global level as per the below screenshot.
I’ve not tried using this in the wild, but preliminary testing suggests it works as intended.
I’d be interested to hear if anyone has any comments and/or alternative/better solutions.
All the best,
Ian