Working with path at module level?

Hello,

I have a package with directories structured like this:

  • Packgage
    • data
      • datafile.txt
    • src
      • package.jl

In package.jl, there is a function

function foo()
    f = read("data/datafile.txt")
    #do smth
end

This works fine when I am working in the Julia environment “Package”, but I would like someone to be able to add Package, using Package, Package.foo().
But in that case, they obtain a SystemError: opening file "data/datafile.txt": No such file
This is because they are in another environment than that of the package. Is there a way to tell Julia to use paths that are within the package?

You could use one of @__FILE__ or @__DIR__ to get the location of the current file.

function foo()
    f = read(joinpath(@__DIR__, "..", "data/datafile.txt"))
    #do smth
end

If you need to find the root folder frequently and from different paths within, then you could define a helper function at a fixed location to return the module root path.

1 Like

Amazing, this will do the trick. Thank you.

1 Like