Home > Back-end >  quote all during df to csv in julia
quote all during df to csv in julia

Time:07-12

is there a way to double quote all fields when outputting a DataFrame to a csv in Julia? I am having trouble find an answer with Google.

In python I would add quoting=csv.QUOTE_ALL to df.to_csv(file)

I am having trouble finding something similar with CSV.write(file,df)

CodePudding user response:

You can do the following:

julia> using CSV, DataFrames

julia> io = IOBuffer()
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf,ptr=1, mark=-1)

julia> df = DataFrame(rand(1:10, 3, 5), :auto)
3×5 DataFrame
 Row │ x1     x2     x3     x4     x5
     │ Int64  Int64  Int64  Int64  Int64
─────┼───────────────────────────────────
   1 │     6     10      5      4      4
   2 │     1      9      6      5      3
   3 │     5      4      5      8      4

julia> CSV.write(io, df; quotestrings=true, transform=(col,val)->string(val)) |> take! |> String |> println
"x1","x2","x3","x4","x5"
"6","10","5","4","4"
"1","9","6","5","3"
"5","4","5","8","4"

The trouble is that quotestrings only forces quoting strings (so that when you read back the file numbers are not quoted and correctly parsed) and therefore you need also transform argument to force every value to be written as string.

  • Related