Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add rows to a .csv file

Tags:

julia

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!

like image 780
InkPen Avatar asked Jan 05 '23 23:01

InkPen


1 Answers

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.

like image 125
Colin T Bowers Avatar answered Feb 22 '23 22:02

Colin T Bowers