I need to append rows to a .csv file. Each row contains a vector of integers. Vectors to be added are generated on the fly and I cannot tell in advance how many rows will be added.
I tried to do the following, but it doesn't seem to create a .csv file, nor does it contain each element on a separate row.
s = open( "testfile.txt", "a")
for i in 1:5
x = rand(Int8, 10)
writecsv( s, x)
end
close(s)
Any help is appreciated!
So, you know how to create or over-write a csv file using this:
x = [1 2 ; 3 4 ; 5 6]
filePath = "/someAbsolutePath/temp1.csv"
writecsv(filePath, x)
When you want to append a new row (or multiple rows in one hit), you can also use writecsv
but first you need to explicitly open the file in append mode, and then set the resulting file-identifier as the first argument to writecsv
. Continuing the example above:
fid1 = open(filePath, "a")
writecsv(fid1, [7 8])
close(fid1)
I don't think writecsv
will automatically close
the file upon completion when the first input is a file-identifier, so the final close
statement is very important. Alternatively, you can use the version proposed by @ShaoWeiTeo in the comments to get an automatic close
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With