Now I am writing a small package. I have written several files and put them in the same directory. And some files need to read in or include another file in the same directory. But when I simply write the file name there, Mathematica can not find them. Is there a easy way to keep this portability? Thank for your kindly help!
The solution using
ResetDirectory, given by @celtschk, is perfectly valid. However, personally I try to avoid this method, since you have to be sure that no other piece of code resets the directory during your operations.
Here is an alternative method. There are two cases we can distinguish here:
You are talking about various
.mfiles, into which you split your package. In this case, you can use a very useful system variable
$InputFileName, which returns the full name of the file currently being read. For example, if you read in the following package
BeginPackage["Test`"] $location = $InputFileName EndPackage
Test`$locationvariable will contain the full name of the file containing that package. You can then extract the name of the directory as
and use that to load other files in the same directory.
If you need this for other types of files, such as text files etc, then you will need a full name for at least one such file in any case. Having that, you can also extract the directory name, and use if for other files.
The solution is to use
ResetDirectory to temporarily set the working directory to the one with your files. For example:
SetDirectory["where/your/files/are"] <<foo.m DoSomethingWith["bar.txt"] ResetDirectory (* set the working directory to whatever it was before *)
SetDirectory maintains a stack of previous values, so you can use several nested
I use this function that works both to notebooks and scripts:
So you can test your script in the command line and in the notebook. For more advanced implementation I recomend Leonid answer.