Export an array to a CSV file in Julia

20,457

You need to load DelimitedFiles module and now only writedlm function is supported.

So in order to write an array as CSV file use:

julia> using DelimitedFiles

julia> writedlm( "FileName.csv",  A, ',')

To get the same result with CSV.jl package use:

julia> using CSV, Tables

julia> CSV.write("FileName.csv",  Tables.table(A), writeheader=false)

as Matrix does not support Tables.jl interface so you need to wrap it with Tables.table.

Share:
20,457

Related videos on Youtube

Hayk
Author by

Hayk

Updated on June 06, 2021

Comments

  • Hayk
    Hayk over 2 years

    Given a (2d) array A how to export it into a CSV file with Julia?

    Back in the older versions, I would write

    writecsv( "FileName.csv",  A);
    

    which would dump the array A into the given file. This, however, does not work in version >= 1.0. After some googling, I also tried to use the CSV module doing

    f = open("test.csv", "a+");
    CSV.write(f, A; delim = ',')
    

    but this throws an error

    ERROR: ArgumentError: no default `Tables.rows` implementation for type: Array{Int64,2}
    

    (my array A was of type Int64).

    Does anyone have a working solution for this most trivial question?

  • PatrickT
    PatrickT over 2 years
    Not sure if this is always needed, but note that you may have to add the :auto argument, as in DataFrame(A, :auto). Bogumił, is this the newer practice? Thanks. Quote: "DataFrame constructor from a Matrix requires passing :auto as a second argument to automatically generate column names: DataFrame(matrix, :auto)"
  • Bogumił Kamiński
    Bogumił Kamiński over 2 years
    yes, now :auto is required. I updated the answer with the currently recommended practice - Tables.table which does not copy.