Basic usages: reading and writing data

JLD2 provides a few different options to save and load data:

FileIO interface

The save and load functions, provided by FileIO, are one of the simplest ways to use JLD2. The save function accepts an AbstractDict yielding the key/value pairs, where the key is a string representing the name of the dataset and the value represents its contents:

julia> using JLD2
julia> save("example.jld2", Dict("hello" => "world", "foo" => :bar))

The save function can also accept the dataset names and contents as arguments:

julia> using JLD2
julia> save("example.jld2", "hello", "world", "foo", :bar)

For save and load to automatically detect that you want to save a JLD2 file use the file suffix ".jld2".

If called with a filename argument only, the load function loads all datasets from the given file into a Dict:

julia> using JLD2
julia> load("example.jld2")Dict{String, Any} with 2 entries: "hello" => "world" "foo" => :bar

When called with a single dataset name, load returns the contents of that dataset from the file:

julia> using JLD2
julia> load("example.jld2", "hello")"world"

When called with multiple dataset names, load returns the contents of the given datasets as a tuple:

julia> using JLD2
julia> load("example.jld2", "foo", "hello")(:bar, "world")

jldsave

jldsave makes use of julia's keyword argument syntax to store files. This can be useful, when your data variables already have the correct name, e.g. use jldsave(file; variablename) instead of `save(file, "variablename", variablename)

JLD2.jldsaveFunction
jldsave(filename; kwargs...)
jldsave(filename, compress; kwargs...)
jldsave(filename, compress, iotype; kwargs...)

Creates a JLD2 file at filename and stores the variables given as keyword arguments.

Examples

jldsave("example.jld2"; a=1, b=2, c)

is equivalent to

jldopen("example.jld2", "w") do f
    f["a"] = 1
    f["b"] = 2
    f["c"] = c
end

To choose the io type IOStream instead of the default MmapIO use jldsave(fn, IOStream; kwargs...).

source

Single object storage

If only a single object needs to stored and loaded from a file, one can use save_object and load_object functions.

JLD2.save_objectFunction
save_object(filename, x)

Stores an object x in a new JLD2 file at filename. If a file exists at this path, it will be overwritten.

Since the JLD2 format requires that all objects have a name, the object will be stored as single_stored_object. If you want to store more than one object, use @save macro, jldopen or the FileIO API.

Example

To save the string hello to the JLD2 file example.jld2:

hello = "world"
save_object("example.jld2", hello)
source
JLD2.load_objectFunction
load_object(filename)

Returns the only available object from the JLD2 file filename (The stored object name is inconsequential). If the file contains more than one or no objects, the function throws an ArgumentError.

For loading more than one object, use @load macro, jldopen or the FileIO API.

Example

To load the only object from the JLD2 file example.jld2:

hello = "world"
save_object("example.jld2", hello)
hello_loaded = load_object("example.jld2")
source

File handles

It is also possible to interact with JLD2 files using a file-like interface. The jldopen function accepts a file name and an argument specifying how the file should be opened:

JLD2.jldopenFunction
jldopen(file, mode::AbstractString; iotype=MmapIO, compress=false, typemap=JLD2.default_typemap)

Opens a JLD2 file at path file. Alternatively file may be a suitable IO object.

Options for mode:

  • "r": Open for reading only, failing if no file exists
  • "r+": Open for reading and writing, failing if no file exists
  • "w"/"w+": Open for reading and writing, overwriting the file if it already exists
  • "a"/"a+": Open for reading and writing, creating a new file if none exists, but preserving the existing file if one is present
source

Data can be written to the file using write(f, "name", data) or f["name"] = data, or read from the file using read(f, "name") or f["name"]. When you are done with the file, remember to call close(f).

Like open, jldopen also accepts a function as the first argument, permitting do-block syntax:

using JLD2
jldopen("example.jld2", "w") do f
    write(f, "variant1", 1.0)
    f["variant2"] = (rand(5), rand(Bool, 3))
end

f = jldopen("example.jld2")
v1 = read(f, "variant1")
v2 = f["variant2"]
close(f)
v1, v2
(1.0, ([0.6010508826617866, 0.964576937674573, 0.8365018072400402, 0.11320545822446038, 0.7174153622769193], Bool[0, 0, 0]))

Groups

JLD2 files allow for nesting datasets into groups which may be useful for organizing your data. You may construct groups explicitly:

using JLD2
jldopen("example.jld2", "w") do file
    mygroup = JLD2.Group(file, "mygroup")
    mygroup["mystuff"] = 42
    display(file)
end

or implicitly, by saving a variable with a name containing slashes as path delimiters:

using JLD2
save("example.jld2", "mygroup/mystuff", 42)

Similarly, you can access groups directly:

using JLD2
jldopen("example.jld2") do file
    file["mygroup"]["mystuff"]
end
42

or using slashes as path delimiters:

using JLD2
load("example.jld2", "mygroup/mystuff")
42

When loading files with nested groups these will be unrolled into paths by default but yield nested dictionaries but with the nested keyword argument.

julia> load("example.jld2")ERROR: UndefVarError: `load` not defined in `Main`
Suggestion: check for spelling errors or missing imports.
Hint: a global variable of this name may be made accessible by importing FileIO in the current active module Main
Hint: a global variable of this name also exists in JLD2.
julia> load("example.jld2"; nested=true)ERROR: UndefVarError: `load` not defined in `Main` Suggestion: check for spelling errors or missing imports. Hint: a global variable of this name may be made accessible by importing FileIO in the current active module Main Hint: a global variable of this name also exists in JLD2.

UnPack Extension

When additionally loading the UnPack.jl package, its @unpack and @pack! macros can be used to quickly save and load data from the file-like interface. Example:

using JLD2, UnPack
file = jldopen("example.jld2", "w")
x, y = rand(2)

@pack! file = x, y # equivalent to file["x"] = x; file["y"] = y
@unpack x, y = file # equivalent to x = file["x"]; y = file["y"]
close(file)