`open` and `include` might point to different folders

So, I have this set-up:

  • I have my active Julia folder in VSCode.
  • Within it I have a folder “subfolder”.
  • I am running stuff in the Julia file “subfolder/my_script.jl”

I am running this script:

open("testfile.jl", "w") do file
    write(file, "println(\"Hello world\")")

Thie yields an error. Turns out that open write the file to the main (active) folder, while include checks relative to where my_script.jl is (that is, another folder). Its there a way to deal with this easily (i.e. make them generally point to the same folder). Pressumably there is a good reason for this behaviour (but what?).

Taking a step back, I have a Julia structure my_struct. I have a function custom_serialise(my_struct) which creates a .jl file that when evaluated regenerates my_struct for later on. It also writes it in a nice human-readable format with some annotation/

At the end of custom_serialise(my_struct) I wanted a safety check, which basically loads the written structure and checks that it is equivalent to the one I was meaning to save. However. if the user runs custom_serialise in a file that is different from their active folder, I get a problem with this behaviour, and I am not sure how to deal with it.

You can use include(joinpath(pwd(), "testfile.jl")) to include relative to the active folder.
You may want to use eval(Meta.parse(read("testfile.jl",String))) instead of include Metaprogramming · The Julia Language
Or use something like JSON3.jl or TOML.jl to serialize your struct more safely.

1 Like

Thanks a lot! :slight_smile: That works

Although your problem seems to have been solved, here is the idiom for specifying a path relative to the jl file (not working directory).

joinpath(@__DIR__, "testfile.jl")