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.
Answer
If your notebook is in the top directory, you can use
Import[FileNameJoin[{NotebookDirectory[], "path", "to", "your", "file.xls"}]]
where the string is the relative path from that directory.
If your notebook is elsewhere in the directory tree and you want to set paths relative to a different directory, then you could define a global $ParentDirectory
and then use all paths relative to that by joining strings as in the above example. Then all that the other person needs to do is to set this global value once and they're good. For example:
$ParentDirectory = FileNameJoin[{"absolute", "path", "to", "mathematica"}];
Import[FileNameJoin[{$ParentDirectory, "path", "to", "your", "file.xls"}]
As Albert Retey points out, you can also use ParentDirectory[NotebookDirectory[]]
to give you the parent directory of the notebook's directory. In other words, it is an equivalent of cd ..
from that directory and can be nested as many times as required.
Comments
Post a Comment