Adding more data to a JLD2 file

I’m slow with these things, but I cannot get a JLD2 file to open and save new information.

Using the instructions here

jldopen("example.jld2", "w") do file
    file["bigdata"]
end

Is file supposed to be the name of the file, or is it just supposed to be file?
Is "bigdata" meant to be the name of the vector/array/thing you are saving?

I’ve tried it two different ways, but no file is created and nothing is saved

jldopen("test", "a+") do file
    one_foodweb_result2
end

f = jldopen("test.jld2", "a+")
write(f, "test", one_foodweb_result2)
close(f)

What is incorrect with my code? I am using Julia 1.5 in Atom.

The following code does what you probably want:

using JLD2
mediumdata=randn(5)
@save "example.jld2" mediumdata # create a file with some data

jldopen("example.jld2", "a+") do file
    file["bigdata"] = randn(6) 
    file["smalldata"] = randn(4) # put your data here instead of random
end
# append data

mediumdata=nothing # reset

@load "example.jld2" bigdata mediumdata smalldata

@show bigdata
@show mediumdata
@show smalldata  # here we are

Thank you for your reply. Is it possible this may not work when it is within a function?

using JLD2

function append_jld2(fname, varname, data)
   jldopen(fname, "a+") do file
     file[varname] = data
   end
end

mediumdata=randn(5)
@save "example.jld2" mediumdata # create file

append_jld2("example.jld2", "bigdata", randn(6))


mediumdata=nothing # reset

@load "example.jld2" bigdata mediumdata

@show bigdata
@show mediumdata # here we are
1 Like

Thank you. When I rerun code to add more data, I get

ArgumentError: a group or dataset named one_foodweb_result2 is already present within this group

The file is already made, but I don’t understand why it wouldn’t be able to add more data. This is happening within a function, so the data I want to add is not in the global scope. Perhaps the issue is with adding something to the same object that is saved in the file?

Yes, to my knowledge you can’t “add” anything to an already saved dataset.