Using Put and PutAppend

(shortcut)       (Save)

To save the value of an expression (especially data) from a Mathematica notebook to a text file, use Put or PutAppend.

For example, if ranmatrix is defined as

	ranmatrix = Table[Table[Random[],{4}],{4}]
then the command
	Put[ ranmatrix,  "filename" ]
stores the value of ranmatrix -- in InputForm -- into the file filename. (Using PutAppend instead would append text to an existing file rather than erasing and replacing it.)

To see the contents of a text file in Mathematica, the shortcut is to use double exclamation marks with the name of the file;

	!! filename
	{{0.727202, 0.0872454, 0.700701, 0.78351}, {0.448799,
	0.045556, 0.153753, 0.617802}, {0.04573, 0.644131,
	0.816811, 0.716899}, {0.614648, 0.087827, 0.4567498,
	0.434024}}

To save numerical data (such as the matrix above) to a text file in a form which other software can use -- in particular, without the brackets and commas -- override the default ``InputForm'' by specifying another form explicitly.

	Put[OutputForm[MatrixForm[ranmatrix]], "filename"]
	!! filename
	0.727202     0.0872454     0.700701     0.783513
	0.448799     0.045556      0.153753     0.617802
	0.045730     0.644131      0.816811     0.716899
	0.614648     0.087827      0.456498     0.434024


Shortcut

Use >> as a shortcut for Put, and >>> for PutAppend. (The single arrow, >, has the usual mathematical meaning of ``greater than'', and so is not used for file operations.)

	expr1  >> filename

	OutputForm[TableForm[expr2]]  >>> filename


Save

To store the definitions associated with a symbol, rather than just the current value of an expression, use Save rather than Put. For example, if function f is defined as follows,

	a = 45Sqrt[b];
	f[x_] := 3x^2 - 2x + a;
	f[17] = Pi;
then saving f to a text file preserves the full definition:
	Save["filename", f]
	!! filename

	f[x_] := 3x^2 - 2x + a
	f[17] := Pi
	a = 45 Sqrt[b]
Then this file can be read (in another Mathematica session) using the shortcut

	<< filename
and the symbols a and f will be restored with their full definitions.