Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save data in Julia

Tags:

save

load

julia

Is there a standard way to easily just save any kind of data in Julia. This time I have a tuple with two arrays in it that I want to use again later. Something like this.

a = [1,2,34]
b = [1,2,3,4,5]

save((a,b), "ab")
a, b = load("ab")
like image 636
MogaGennis Avatar asked Dec 30 '22 15:12

MogaGennis


2 Answers

You can use JLD2.jl to save and load arbitrary Julia objects. This is more likely to work for long term storage across different Julia versions than the Serialization standard library.

using JLD2

x = (1, "a")
save_object("mytuple.jld2", x)
julia> load_object("mytuple.jld2")
(1, "a")

For additional functionality, check out the docs.

like image 118
Cameron Bieganek Avatar answered Jan 18 '23 23:01

Cameron Bieganek


There are many scenarios depending on how long you want to store the data

  1. Serialization (this is perfect for short time periods, for longer periods where packages update their internal data structures you might have problem reading the file)
julia> using Serialization

julia> serialize("file.dat",a)
24

julia> deserialize("file.dat")
3-element Vector{Int64}:
  1
  2
 34
  1. Delimited files (note that additional processing of output might be needed)
julia> using DelimitedFiles

julia> writedlm("file.csv", a)

julia> readdlm("file.csv", '\t' ,Int)
3×1 Matrix{Int64}:
  1
  2
 34
  1. JSON (great for long term)
julia> using JSON3

julia> JSON3.write("file.json",a)
"file.json"

julia> open("file.json") do f; JSON3.read(f,Vector{Int}); end
3-element Vector{Int64}:
  1
  2
 34

Other worth mentioning libraries (depending on data format) include CSV.jl for saving data frames and BSON.jl for binary JSON files.

like image 26
Przemyslaw Szufel Avatar answered Jan 19 '23 01:01

Przemyslaw Szufel