How do I save the output to .txt file?

Hey People,

right now I’m struggling with saving my data.

By using a for loop and the println() command, my programm is giving me out a bunch of named arrays like this in the following:

for n = 1:10
a = rand(1:10, 4)
println("a$n = ",a)
end

now my question is:
how do I save the output from the console (REPL) as a text oder csv file ?

1 Like

It is not clear from your question what is exactly your end goal- do you just want to direct println statements to a text file? Do you have some array that you want to save to a file? Do you want to save all the output in a REPL session to a file?
If you could clarify your end goal you might get better help.

In any case, if what you want is to direct println statements to a file you could do something like:

open("file.txt","a") do io
   println(io,"a=",a)
end

But I’m not sure that this is really what you want.

7 Likes

Well, my goal is to save the println() statements to a text file.
In this example I mentioned, I do receive (in this case 9) arrays, which I would like to have saved in a text file.

Could you explain what the “do io” command actually does and why there is “a” in the argument of open()?

Have a look at the documentation, which you can also access from the REPL by typing ? open and ? do.
If you still have questions after reading the documentation feel free to ask.

Depending on what exactly it is that you do, I don’t think the optimal solution is to print the arrays into a text file like this. Maybe you can organize all your data in a dataframe which you can then more easily manipulate and save/load from file.

You could also use a package like JLD2 which allows you to save and load Julia objects in a format similar to HDF5.

3 Likes

well I did check the documentation already, but it is still not really plausible to me what “do io” is actually good for and why it is continued in the argument of write() or println() … .

thanks for your advise, I’ll check out how to work in a dataframe and if there are still any questions I’ll let you know !

You should read the documentation. But my understanding is that the suggested syntax makes sure that the file is automatically closed/released after end.

1 Like

On the do block, see https://docs.julialang.org/en/v1/base/base/#do

How it relates to file IO is described in Networking and Streams.

Calling open with a function (implicitly created by do) is a shortcut for (1) open; (2) call function on the IOStream; (3) close.

5 Likes

Maybe it will help reading about anonymous functions to better understand the do syntax.

2 Likes

thank you so much !
working with data frames is way more convenient, than anything I tried before.
It’s like having a flexible storage for a bunch of arrays/data wich can be easily saved !

2 Likes

If you are using DataFrames, use CSV.jl to save things to a text file.

2 Likes