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!
Answer
The solution using SetDirectory
/ 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
.m
files, 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 packageBeginPackage["Test`"]
$location = $InputFileName
EndPackage[]then the
Test`$location
variable will contain the full name of the file containing that package. You can then extract the name of the directory asDirectoryName[$InputFileName]
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.
Comments
Post a Comment