I Cannot find how to use relative paths in mathematica. My directory structure is simple.
Import["G:\\Research\\Acc and Vel Runs\\5-24\\Mathematica\\Data\\250 \
Acc.xls"][[1]] // TableForm
That Demonstrates the Absolute path by using the insert path from the menus. I want this notebook to be portable. I want to give someone the "Mathematica" directory and I want them to be able to run the code. I don't want the paths to break because It will be run on a different machine. Basically I just want to use a relative path starting at the Mathematica level shown above.
In Mathematica you can get the current directory using Directory[]
and you can set it to something else using SetDirectory[]
. You can go back to the last location using ReserDirectory[]
or check all previous locations using DirectoryStack[]
.
This is described in the documentation here.
You can set the current directory to the directory where the notebook is using
SetDirectory[NotebookDirectory[]]
For NotebookDirectory
to work, you must be using the Front End and the notebook must be saved.
You can always use path relative to the current directory (Directory[]
), for example Import["data/somedata.txt"]
.
Regarding directory separators: /
will always works, on all of Windows/Linux/Mac. When you are typing a relative path name, it's much more convenient to just use /
for portability than FileNameJoin
.
I usually do this.
SetDirectory[
FileNameJoin[{$InitialDirectory, "dir1", "dir2"}]];
Quiet[Close["Log.txt"]];
logStream = Quiet[OpenWrite["xmlAreaTagsLog.txt"]];
xmlDoc = Import["XmlData.xml"];
Using $InitialDirectory gets you the .nb directory and using FileNameJoin allows you to have relative access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With