Storing an array in CSV file

i’m getting confused with this simple working example, for some reason i do not get my array stored in the CSV file:

arr=[0,1]
open("out.csv","a")
CSV.write("out.csv",(arr=arr))
CSV.read("out.csv")

and as an output i get this:
0 rows × 0 columns

i am expecting the array to be stored in the file without any problems but the file is still empty .

Without having checked this, a problem could be that you’re not actually constructing a named tuple with (arr = arr). This expression assigns arr to arr, just within parentheses so it almost looks like a named tuple. For one element named tuples you either have to add a comma like (arr = arr,) or I think (; arr) also works, or the more verbose (;arr = arr)

3 Likes

what about if i’m having more than one value to store which one of them is a scalar, something like this

for i = 0:4
    beta = i*pi/4
    arr=[i,i/2]
end

and i want to save both beta and arr
i tried this
CSV.write(("out.csv",(all_results=all_results;beta=[beta]))
but it didn’t work.

That example is a bit hard to understand. Where does all_results come from? Your for loop overwrites beta and arr in each iteration, did you mean to collect elements?

Also, the syntax (all_results=all_results;beta=[beta]) is not correct for a named tuple, the semicolon can only go at the beginning, but you don’t even need that. The semicolon is for this convenience syntax:

a = 1
b = 2

julia> nt = (; a, b)
(a = 1, b = 2)

Then you’re passing a superfluous tuple to CSV.write, you don’t need the extra parentheses around the two arguments.

Last but not least, if you need to store a column which only consists of the same repeated scalar, try fill(value, number_of_elements) to create such a vector.

2 Likes

i apologize for that all_results i wanted to write arr instead