Save variable

Hi everyone,
Sorry for the elementary question.
How do I save any variables after a program runs in Julia?
Could someone give me an example of how to save the variable “a” in a file .dat in this code?

global a
for i in 1:10
a = a+i
end

There’s a few options but JLD2 works fine for me :

using FileIO, JLD2
a = 1
FileIO.save("myfile.jld2","a",a)
b = FileIO.load("myfile.jld2","a")

You can also use CSV or DelimitedFiles if you just want to save data in a text file.

The built-in serializer can be quite nice to use in some cases.

using Serialization

a = randn(100,100)
f = serialize("file1.dat", a)

a′ = deserialize("file1.dat")

println(a == a′)

Note however that the built-in serializer is designed for inter-process communication (IPC) and not really for stashing data on disk. Therefore, serialized data output by one version of Julia is not guaranteed to be readable by other versions of Julia, so this is most definitely not for long-term storage. It can however still be extremely useful if you are only looking for short-term storage of things which are reproducible. Last I checked, the serializer was quite fast.

2 Likes

Also, this doesn’t do what you think it does and wouldn’t work. My suggestion is to stay in jupyter notebooks as you are learning, and just drop that global. That is, use

a = 0
for i in 1:10
   a = a+i
end

If you want to do this in a file or in Atom/Juno, then put a function around it.