Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative paths for portable notebooks in mathematica

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.

like image 406
Matthew Kemnetz Avatar asked May 24 '12 22:05

Matthew Kemnetz


2 Answers

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.

like image 93
Szabolcs Avatar answered Oct 01 '22 22:10

Szabolcs


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.

like image 42
stuartw Avatar answered Oct 01 '22 21:10

stuartw