4
votes

I'm creating a package in Julia and have followed the Package Development section of the Docs.

One of my functions opens and reads in a data file (mydata.txt) that I'm storing in the package directory.

Everything works pretty great when I run the Julia from the package directory but not so great when I run the tests or run Julia from a different directory because it doesn't know where to find that data file.

I thought I could just do something like:

datapath = Pkg.dir("MyPkg") * "/data/"

to get an absolute path to the file but it still doesn't seem to work.

What is the correct way to provide an absolute file path for data in a package?

3
What OS are you on, what version of Julia, and just how did that not work? Normally, you should use joinpath instead of concatenation when building a directory. - Scott Jones
Mac. Julia 0.4.5. Basically just doesn't find the file. Thanks for the joinpath tip, I'll give it a shot. - Ellis Valentiner
joinpath(Pkg.dir("MyPkg"), "data", "mydata.txt") should work. - Imanol Luengo
@imaluengo I think you should post your comment as an answer. - niczky12
@niczky12 Thx! done. Forgot about this question. - Imanol Luengo

3 Answers

6
votes

In order to properly handle multi-platform directory files and paths, use Julia's built-in joinpath method:

joinpath(Pkg.dir("MyPkg"), "data", "mydata.txt")

The resulting path will be valid in every platform.

5
votes

As of Julia 1.0, the answer by Imanol Luengo will produce a warning:

Warning: Pkg.dir(pkgname, paths...) is deprecated; instead, do import PackageName; joinpath(dirname(pathof(PackageName)), "..", paths...)"

so while it still works, it will stop working in a future version. The replacement suggested in the warning message seems to work:

joinpath(dirname(pathof(MyPkg)), "..", "data")

Inside the package you don't need the import.

0
votes

In Julia 1.7 and above, you can simply do:

datapath = pkgdir("MyPkg", "data")
mytxtpath = pkgdir("MyPkg", "data", "mydata.txt")
# etc. - any number of path components are allowed as further arguments

For earlier versions (from either 1.3 or 1.4 version), replace Pkg.dir in @ImanolLuengo's answer with pkgdir:
joinpath(pkgdir("MyPkg"), "data", "mydata.txt")