Reputation: 233
I'm using Julia. I would write a single row again and again on existed CSV file. I think 'CSV.RowWriter' can make it happen, but I don't know how to use. Can anyone show me an example?
Upvotes: 2
Views: 453
Reputation: 69839
CSV.RowWriter
is an iterator that produces consecutive rows of a table as strings. Here is an example:
julia> df = DataFrame(a=1:5, b=11:15)
5×2 DataFrame
Row │ a b
│ Int64 Int64
─────┼──────────────
1 │ 1 11
2 │ 2 12
3 │ 3 13
4 │ 4 14
5 │ 5 15
julia> for row in CSV.RowWriter(df)
@show row
end
row = "a,b\n"
row = "1,11\n"
row = "2,12\n"
row = "3,13\n"
row = "4,14\n"
row = "5,15\n"
You would now just need to write these strings to a file in append mode.
Most likely, since you want to append you want to drop he header. You can do it e.g. like this:
julia> for row in CSV.RowWriter(df, writeheader=false)
@show row
end
row = "1,11\n"
row = "2,12\n"
row = "3,13\n"
row = "4,14\n"
row = "5,15\n"
If you want me to show how to write to a file please comment.
The reason why I do not show it is that you do not need to use CSV.RowWriter
to achieve what you want. Just do the following:
CSV.write(file, table, append=true)
EDIT: example of writing with CSV.RowWriter
:
julia> using DataFrames, CSV
julia> df = DataFrame(a=[1, 2], b=[3, 4])
2×2 DataFrame
Row │ a b
│ Int64 Int64
─────┼──────────────
1 │ 1 3
2 │ 2 4
julia> isfile("test.txt") # make sure the file does not exist yet
false
julia> open("test.txt", "w") do io # create a file and write with header as the file does not exist
foreach(row -> print(io, row), CSV.RowWriter(df))
end
julia> readlines("test.txt") # chceck all is as expected
3-element Vector{String}:
"a,b"
"1,3"
"2,4"
julia> open("test.txt", "a") do io # append to file and write without header
foreach(row -> print(io, row), CSV.RowWriter(df, writeheader=false))
end
julia> readlines("test.txt") # check that all is as expected
5-element Vector{String}:
"a,b"
"1,3"
"2,4"
"1,3"
"2,4"
Upvotes: 4