Re: Appending 2D arrays to files?
- To: mathgroup at smc.vnet.net
- Subject: [mg49196] Re: [mg49151] Appending 2D arrays to files?
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Wed, 7 Jul 2004 01:42:31 -0400 (EDT)
- References: <200407050854.EAA14779@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
On Jul 5, 2004, at 4:54 AM, Jonathan Greenberg wrote: > This is a followup to the "Joining 2D arrays" question -- thanks to > everyone > who replied. If I want to append a 2D array of a fixed column width > but > arbitrarily long number of rows to a CSV file (so I'm adding new rows > to the > file after each output of my model), how do I do this? The easiest way is probably to use Export to write to a set of CSV files and then use a script to concatenate the files together. For example in Unix, assuming the CSV files have names of the from datan.csv where n is some integer then cat data*.csv > result will concatenate them into a file named result. If you want to do this entirely within Mathematica, the following function writeascsv will append a 2D matrix to a file in CSV format. Just keep the file open during your run. interleave[a_, b_] := Block[{la = Length[a], lb = Length[b], l, r}, r = Range[Min[la, lb]]; l = Flatten[Transpose[{a[[r]], b[[r]]}], 1]; If[la > lb, Append[l, Last[a]], l]] writeascsv[chan_,mat_]:=WriteString[chan, ##, "\n"] & @@@ (interleave[#, Table[ ",", {Length[#] - 1}]] & /@mat) A less complicated way to accomplish this is to use PutAppend (>>>). Write all your matrices as Mathematica expressions to a file then use Export["resultfilename.csv",Join@@ReadList["fileofexpressions"]] The drawback to this technique of course is that an extra copy of the data is left in a file. Regards, Ssezi
- References:
- Appending 2D arrays to files?
- From: Jonathan Greenberg <greenberg@ucdavis.edu>
- Appending 2D arrays to files?