Relative paths for portable notebooks in Mathematica

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.


Since FileNameJoin was only introduced in Mathematica v7, I thought I'd add a solution using ToFileName for people still running earlier versions (like me):

Import[ToFileName[{
  NotebookDirectory[], "path", "to", "directory"},
  "file.xls"]]

So it works in a similar way, but notice that while the path to the file is enclosed in the {...}, the actual file goes separately.


I realise that this is an old question but I think the following option should also be considered:

SetDirectory[NotebookDirectory[]];

Adding this line at the beginning of your notebook will essentially tell Import to look for your file in a path relative to where your notebook is saved. This method obviously only works after the notebook has been saved!