Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return one folder above current directory in Julia

In Julia, I can get the current directory from

@__DIR__

For example, when I run the above in the "Current" folder, it gives me

"/Users/jtheath/Dropbox/Research/Projects/Coding/Current"

However, I want it to return one folder above the present folder; i.e.,

"/Users/jtheath/Dropbox/Research/Projects/Coding"

Is there an easy way to do this in a Julia script?

like image 726
Joshuah Heath Avatar asked Mar 02 '23 19:03

Joshuah Heath


1 Answers

First, please note that @__DIR__ generally expands to the directory of the current source file (it does however return the current working directory if there are no source files involved, e.g when run from the REPL). In order to reliably get the current working directory, you should rather use pwd().

Now to your real question: I think the easiest way to get the path to the parent directory would be to simply use dirname:

julia> dirname("/Users/jtheath/Dropbox/Research/Projects/Coding/Current")
"/Users/jtheath/Dropbox/Research/Projects/Coding"

Note that AFAIU this only uses string manipulations, and does not care whether the paths involved actually exist in the filesystem (which is why the example above works on my system although I do not have the same filesystem structure as you). dirname is also relatively sensitive to the presence/absence of a trailing slash (which shouldn't be a problem if you feed it something that comes directly from pwd() or @__DIR__).

I sometimes also use something like this, in the hope that it might be more robust when I want to work with paths that actually exist in the filesystem:

julia> curdir = pwd()
"/home/francois"

julia> abspath(joinpath(curdir, ".."))
"/home/"
like image 66
François Févotte Avatar answered Mar 17 '23 08:03

François Févotte