# How to export CSV from Mathematica?

I have previously been using

logf[x_, y_] := f[x, y] /. v_ :>(PutAppend[Unevaluated[f[x, y] = v;], "out.txt"];);

which produces output like f[1,5]=2.566665345435; on each line of the output file. How could I modify this to produce CSV file, i.e. output lines that look like

1, 5, 2.5666665345435
3, 4, 4.4353453453453
.
.

I tried the obvious guess

logf[x_, y_] := f[x, y] /. v_ :>(PutAppend[Unevaluated[x, y, v], "out.txt"];);

but this does not work, as the word "Sequence" also gets exported.

Also is this the best way I can export data from Mathematica to be read in by c++ code or is there a better way?

• I think you should explain the big picture of what you are doing, otherwise it is impossible to suggest a "better" or even "good" way. Things of interest are e.g. necessity to write line by line vs. writing on block, efficiency requirements and/or amount of data to read/write and what possibilities (libraries) there are available to read data on the C++ side, will the data be read on the same computer as it is written, do you need the file be human readable also. Every other bit of additional information will help others to give better answers... Nov 23 '12 at 9:28
• Basically this is a function of two variables that sets some initial conditions for each point in the parameter space, i.e. maybe f[1,2]=2.3+9.8I. The c++ code needs to read this in and then I basically want to store in some object that resembles a function (I was thinking of using map with x,y as a key and the complex value of the function at (x,y) as the value but maybe there is a better way). There is no necessity for the file to be human readable, but it could be read on other computers. Nov 23 '12 at 13:10
• There is a lot of data, but I don't think space is a massive concern, but if you know a better way to store the data file, and retrieve it in the c++ code so that I have something like a function in c++ I'd be happy to consider going that way Nov 23 '12 at 13:11
• as you are storing very uniform data and have a lot of data, you should think about storing those values in a binary file. You'd need a combination of OpenWrite or OpenAppend, BinaryWrite and Close. With BinaryWrite you can store numeric data as reals of various bitlengths or even as complexes. For details you might want to search those functions and BinaryRead in the documentation. It should be relatively easy and very efficient to read these files from c++. As long as the "endianness" is the same it shouldn't be a problem to read those files on another computer... Nov 23 '12 at 23:53

• Is there a way to make sure the numeric values of f[x,y] are in C-style scientific notation,e.g. not 1.7736782427799868006160419897172935521449567176544099319450645855950.*^7 but something like 1.77367824277998680061604198971729355214495671765440993194506458559e^7 i.e. using e and not using the "50" precision notation Nov 23 '12 at 20:27